Learn one way to render SVG icons as a React component. You’ll learn about the dynamic nature of SVG by passing props to a component that modify the icons properties such as colors and size.
You'll learn how to set up a stateless functional component, set up prop types and add a set of default props.
One benefit to building an individual icon component is that only the SVG markup needed for that icon will be rendered, instead of having to load an entire set of icons and only using one of them. Also, different attributes can be overridden using props, making theming and integration simple.
I've got a base application class that renders a div. I'm using React dom to render that application class to an ID of app. Inside the render method, let's render a new component by typing location icon. This component doesn't exist yet, so let's go ahead and do that now.
Because this icon won't need any state, we'll be making a stateless functional component. Let's start by typing const location icon. That's going to be a function. I'll use the arrow function syntax. I'll open and close parentheses. Inside the return body, I'll paste our location icon SVG.
With this, you can see our main component is rendering the location icon component. Let's improve this location icon component by adding the ability to change some properties on the fly. Let's start by defining some prop types so a consumer of the icon knows what type of prop to pass.
We'll start by typing location icon, prop types. Say a width, set that to React.proptypes.number, as well as for height. Next, I'll add some default props by saying location.icon default props. Set a width of 128 and a height of 128.
All that's left to do is apply those props to the SVG itself. In the component function declaration, we can destructure the props to make them easier to use. Let's add curly braces. Inside, I'll add width and height. Inside of the SVG tag, I'll add a width attribute.
I'll set it equal to width and set height as equal to height. In our case, we're rendering a location icon, but we're not passing a width and height as props so our default props are kicking in. We'll add two more props. I'll say pin fill. That's going to be React.proptypes.string. We'll say base fill as well as dome default props for each.
Next, I'll add those props to our component function declaration. We'll add those props to the SVG itself by saying fill and setting its value here to pin fill. Second, I'll add fill of base fill. Again, since we haven't added any props to this location icon, all of our default props are kicking in.
If I add another location icon, this time let's pass some props. I'll pass a width of 200 and a height of 200. I'll add pin fill and base fill. The icon on the left here is our default icon with all of our default props. The icon on the right is the icon where we've overridden all those default props.