Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass optional elements to a component as a prop in reactjs

I am trying to figure out the proper "react" way to pass in an optional prop that is an Element to a container component, that is handled differently from the children of that component.

For a simple example, I have a Panel component, which renders its children, that also has an optional "title" prop (which is an element rather than a string, for the sake of the example) that gets specially rendered (put in a special spot, with special behaviors in while maintaining the abstraction.

One option is to have a component which is pulled out of the children and rendered specially:

<Panel>
   <Title> some stuff</Title>
   <div> some other stuff</div>
</Panel>

But it seems wierd to have the children pulled out and handled separately like that.

How is this normally handled in react, and am I even thinking about this the right way

like image 963
Zak Kus Avatar asked Nov 10 '15 21:11

Zak Kus


People also ask

How do you pass optional function as props in React?

To set optional props with default values in React TypeScript: Mark the props on the type as optional using a question mark. Provide default values for the props when destructuring them in the function's definition.

How do I pass optional props to component?

To pass optional elements to a component as a prop in React, we can create a component that accepts the children prop. We defined the Panel and Title components that take the children prop. children can take one or more React components or strings. We set 'hello world' as the value of Title 's children prop.

Can we pass component as a prop in 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 add additional props to a React element passed in as a prop?

You can also just pass the component and props to the child elemnt, fully destructure your component and props, then render it as a JSX element. You then can spread your props into the passed component. This way your child component reusable and you can change its props from the parent component.


1 Answers

You don't need to do anything special. Just pass the title component as a prop, and then use {this.props.title} wherever you want it to be rendered:

class Panel extends React.Component {
  render() {
    return <div>
      {this.props.title}
      <div>Some other stuff...</div>
    </div>;
  }
}

class App extends React.Component {
  render() {
    var title = <Title>My Title</Title>;
    return <Panel title={title}/>;
  }
}

If you don't pass any value for the title prop (or if the value is false, null, or undefined) then nothing will be rendered there.

This is a fairly common pattern in React.

like image 87
Jordan Running Avatar answered Sep 17 '22 03:09

Jordan Running