Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React props vs children. What to use when?

Tags:

reactjs

What is the difference between the two approaches ?

Passing text for a button as props

<TextComponent title="Save"/>

function TextComponent(props){
  return <button>{props.title}<button/>
}

vs

Passing text as a child

<TextComponent>Save<TextComponent />

function TextComponent(props){
  return <button>{props.children}<button/>      
}
like image 548
Umair Avatar asked May 06 '19 11:05

Umair


People also ask

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

Essentially, props. children is a special prop, automatically passed to every component, that can be used to render the content included between the opening and closing tags when invoking a component. These kinds of components are identified by the official documentation as “boxes”.

Why would you use React children?

React. Children. map is a utility function to help you handle different cases. Invokes a function on every immediate child contained within children with this set to thisArg.

Why do we need props children?

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

children prop is something that you use when the structure of what needs to be rendered within the child component is not fixed and is controlled by the component which renders it.

However if behaviour of the component is consistent across all its renders it can define the specific props that it needs and the parent can pass them to it.

A very simple example could be a Navbar which can use children. For a Navbar the items that it needs to render as well as the order or alignment or items depends on how it needs to be used at different instances or across different pages. For instance Navbar somewhere can have Search component at one place and at some other place not have it. Also the menus may sometimes be needed to the left followed by Login menu item to the right and a searchbar between them and sometimes they may all be present to the right without the searchbar. In such cases the parent component can control how the internal structure would be

like image 113
Shubham Khatri Avatar answered Oct 04 '22 20:10

Shubham Khatri