5

I am creating a react functional component in which I want to display an icon.

function Item(props) {
    return ({props.icon});
}

and I display it like this -

<Item icon={<FaIcon />} />

Is there a way to pass in props to the icon from the Item component?

Something like this -

function Item(props) {
    return ({props.icon(props: {})});
}
SuPythony
  • 875
  • 8
  • 23
  • The easiest way would be to pass the component instead of the rendered element, `` and let the `Item` render the icon with the right props. – Emile Bergeron Aug 17 '21 at 17:37
  • 4
    Otherwise, you're essentially asking: [How to pass props to {this.props.children}](https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children) – Emile Bergeron Aug 17 '21 at 17:38

2 Answers2

4

Just render it like any other component

first you need to send the raw component as a prop

<Item icon={FaIcon} />

Then you render it like a component

function Item(props) {
    return (<props.icon /* Here goes the props */ /> );
}
pablo henrique
  • 332
  • 3
  • 10
  • Ok, thanks! But everywhere the icon is used, it is shown like this only - . Why is it so? – SuPythony Aug 17 '21 at 18:27
  • It's not working I am getting this error - `Invalid value for prop 'icon' on
    tag. Either remove it from the element, or pass a string or number value to keep it in the DOM`
    – SuPythony Aug 17 '21 at 18:38
  • Oh, sorry, it works! I was messing up as I had not updated the other instances of the component – SuPythony Aug 17 '21 at 18:43
0

You could also use props.children like this:

function Item(props) {
    return (<>{ props.children }</>);
}

<Item>
   <FaIcon /* child props over here */ />
<Item>

But this only sets props from where component is called and not within the parent component Item. If you exactly want to set props within Item component the best answer would be the same as what @pablo-henrique said:

function Item(props) {
    return (<props.icon /* Here goes the props */ /> );
}

<Item icon={FaIcon} />
Farhad Rad
  • 563
  • 2
  • 15