Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an inline SVG as React component prop

Tags:

reactjs

svg

Is this possible to pass an inline SVG as component prop (and not as component child). I tried with a method like below but that doesn't work :

 mySvg1() {
   return (<svg xmlns="... ></svg>);
 }

 render() {
   <AnotherComponent icon={this.mySvg()} />
 }
like image 501
Jerome Avatar asked Aug 02 '17 17:08

Jerome


People also ask

How do I import SVG into React component?

To do this, open up the SVG file in a text editor, and copy-paste the code into a new component: export const ArrowUndo = () => { return ( <svg xmlns="http://www.w3.org/2000/svg" className="ionicon" viewBox="0 0 512 512" > <path d="M245.

Can you pass a React component as prop?

You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop.

Can you pass arrays as props in React?

To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements.

Can we pass props to functional component?

Of course, you can still pass props from parent to child with functional components but the big difference is that you'll need to declare them in your functional component callback just as you would with any other type of function. Now you can access those props.


2 Answers

Yes, it's possible. But first you need to define the Icon component.

// MySvgIcon.js
function MySvgIcon() {
  return (<svg xmlns="..."></svg>);
}

Once you have the component, you will need to define the other component and use the Icon as follow:

// AnotherComponent.js
function AnotherComponent({ Icon }) {
  return (<div>A nice icon: <Icon /></div>);
}    

And you can use them like this:

// OtherComponent.js
function OtherComponent() {
  return (<AnotherComponent Icon={MySvgIcon} />);
}
like image 167
Crysfel Avatar answered Sep 29 '22 20:09

Crysfel


Try to import SVG as React Component as shown

import { ReactComponent as AnyName } from '../pathtosvg';

render() {
   <AnotherComponent Icon={AnyName} />
}

Make sure prop name is capitalized otherwise it won't work if you destructure your props in AnotherComponent. But if you are not destructuring then props.anyNameWouldWork (no need to capitalize).

like image 32
Tarun Gupta Avatar answered Sep 29 '22 19:09

Tarun Gupta