Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Pass component as prop without using this.props.children

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

like image 579
sandrina-p Avatar asked Feb 28 '17 14:02

sandrina-p


People also ask

Can you pass a component as a prop React?

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.

How do you pass a prop to child component?

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.

What is the best way to send 4 or more props to a child component?

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.

What is this props children and when you should use it?

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.


1 Answers

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/

like image 63
pawel Avatar answered Oct 16 '22 17:10

pawel