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()} />
}
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.
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.
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.
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.
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} />);
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With