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(props) {
      super(props);
      this.element = document.createElement('div');
}

I have a svg imported to the the component like below import SvgName from '../svg/name.svg';

and want to append this SvgName to the div element created dynamically in the above constructor.

What i have tried....is below,

constructor(props) {
      super(props);
      this.element = document.createElement('div');
      const svg = document.createElement('svg');
      this.element.appendChild(svg);
}

The above will append a svg element however it doesnt add the svg that i want (the one imported).

How can i achieve it. Thanks.

Answers:

Answer

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.

Answer

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

Answer

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>
  }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.