How to use svg from the folder path in appendchild method javascript or reactjs?

前端 未结 3 2055
别那么骄傲
别那么骄傲 2021-01-24 01:11

i am new to reactjs and i stuck with appending svg element to the div element.

What is that i want to implement? I have a div element created dynamically like below.

相关标签:
3条回答
  • 2021-01-24 01:46

    The svg element in your example is a react component, so it can be rendered inside DOM elements with ReactDOM.render, like that:

    componentDidMount() {
        ReactDOM.render(<SvgComponent />, this.element);
    }
    

    The ReactDOM.render call does not necessarily have to be in the componentDidMount handler, you can use it in whatever part of the lifecycle of the component you feel like, as long as this.element is an initialized DOM element.

    0 讨论(0)
  • 2021-01-24 01:46

    If you want to create element dynamically I would suggest you to use your Component's state. In react it is not good practice to operate with DOM directly like you do. So your code should looks like:

    import React from "react";
    import {ReactComponent as SvgName} from '../svg/name.svg'
    
    class SomeClass extends React.Component {
      state = {
        renderImage: false,
      }
    
      componentDidMount() {
        if(someConditionMets) {
           this.setState({renderImage: true});
        }
      }
    
      render() {
        if (this.state.renderImage) return <div><SvgName /></div>;
    
        return null;
      }
    }
    
    export default SomeClass;
    

    Or if you want your div to render every time you can change render method to:

      render() {
        return <div>{this.state.renderImage && <SvgName />}</div>
      }
    
    0 讨论(0)
  • 2021-01-24 01:54

    From the create-react-app

    One way to add SVG files was described in the section above. You can also import SVGs directly as React components. You can use either of the two approaches. In your code it would look like this:

    import { ReactComponent as Logo } from './logo.svg';
    const App = () => (
      <div>
        {/* Logo is an actual React component */}
        <Logo />
      </div>
    );
    

    This will load the svg as component and you can use it.

    Full Read here

    0 讨论(0)
提交回复
热议问题