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