Skip to content Skip to sidebar Skip to footer

How To Use Svg From The Folder Path In Appendchild Method Javascript Or Reactjs?

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. constructor(

Solution 1:

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 { ReactComponentasLogo } from'./logo.svg';
constApp = () => (
  <div>
    {/* Logo is an actual React component */}
    <Logo /></div>
);

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

Full Read here

Solution 2:

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.

Solution 3:

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:

importReactfrom"react";
import {ReactComponentasSvgName} from'../svg/name.svg'classSomeClassextendsReact.Component {
  state = {
    renderImage: false,
  }

  componentDidMount() {
    if(someConditionMets) {
       this.setState({renderImage: true});
    }
  }

  render() {
    if (this.state.renderImage) return<div><SvgName /></div>;

    returnnull;
  }
}

exportdefaultSomeClass;

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

render() {
    return<div>{this.state.renderImage && <SvgName />}</div>
  }

Post a Comment for "How To Use Svg From The Folder Path In Appendchild Method Javascript Or Reactjs?"