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/>
}
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”.
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.
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.
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
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