I have this a component Foo.js
:
// a svg component with a star.svg icon
import { IconStar } from 'react-svg-icons';
// call a button with a custom icon
<Button icon={ IconStar }> Click to trigger </Button>
And then on button.js
I have:
render() {
const theIcon = this.props.icon;
return (
<button>
{this.props children}
{icon() /*this works but i can't pass props inside it*/}
<theIcon className={ Styles.buttonIcon } />
</button>
)
}
I want to render <IconStar>
inside <Button>
, how do I do that?.
I can't pass this as this.prop.children
because it has more logic around the icon prop, but in this case I'm showing only a demo.
Thanks
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 props, add them to the JSX, just like you would with HTML attributes. To read props, use the function Avatar({ person, size }) destructuring syntax. You can specify a default value like size = 100 , which is used for missing and undefined props.
Instead, to pass all React props from parent to child at once, you need to take advantage of the spread operator ( ... ). The spread operator lets you pass the entire props object to a child component as that child's props object.
Props is simply an abbreviation for properties. In React, we utilize props to send data from one component to another (from a parent component to a child component or multiple children components). They come in handy when you want the data flow in an app to be dynamic.
The only thing you have missed is that for JSX to transpile to JS custom components should be named starting with a capital letter, e.g. <TheIcon />
, while lowercase letter signifies native DOM elements, e.g. <button />
.:
render() {
const TheIcon = this.props.icon; // note the capital first letter!
return (
<button>
{this.props.children}
<TheIcon className={ Styles.buttonIcon } />
</button>
)
}
https://jsfiddle.net/03h2swkc/3/
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