'How do you pass different props to different child components in a parent component?
I'm trying to understand the rendering in ReactJS. I'm following this tutorial from YouTube, but I want a better grasp on the subject. The video explains that if you pass down the child component
<Child/>
Then it will trigger a render of the parent and the child. However if you pass down
{props.children}
Then it will only update the parent, if there are no changes to the children. But what if I have a series of different children? What if I have 20 children or 100? And I want to pass a prop to a specific child? Say I want to pass down a prop to the 50th child (or any other). Then how would I go about in doing this?
Say that I want to pass down these constants, would the children only re-render if they receive a prop or would they all re-render?
const [childA, setChildA] = useState("In Child A")
const [childB, setChildB] = useState("In Child B")
I tried using the code from How to pass props to {this.props.children}
{React.Children.map(props.children, function(child){
if(React.isValidElement(child)){
let clone = React.cloneElement(child, {...props})
return clone
}
But I'm not sure what I'm doing, I'm think I'm in the right path, but I'm not sure how to get what I'm looking for.
Parent component
import React, { useState } from 'react';
function ParentCount(props) {
const [count, setCount] = useState(0)
console.log("Parent render")
return (
<div>
<button onClick={()=>setCount(v=>v+1)}>Parent Increase +1</button>
Parent count is {count}
Children count
{React.Children.map(props.children, function(child){
if(React.isValidElement(child)){
let clone = React.cloneElement(child, {...props})
return clone
}
})}
</div>
);
}
export default ParentCount;
App component
function App() {
return (
<div className="App">
<ParentCount>
<ChildCount></ChildCount>
<ChildCount></ChildCount>
</ParentCount>
</div>
);
}
export default App;
Child component
import React, {useState} from 'react';
function ChildCount(props) {
const [count, setCount] = useState(0)
console.log("Child render")
return (
<div>
<button onClick={()=>setCount(v=>v+1)}>Child Increase +1</button>
<div>Child count is {count}</div>
</div>
);
}
export default ChildCount;
Solution 1:[1]
the meaning of the first lines you wrote is this:
if you pass a prop to a child component, react will only update that component for you. ex:
<ChildComponent prop1 = 'hi'>
if you add a whole new child component to your Component, react will update your parent too:
function ParentComponent () {
const [update, setUpdate] = useState(0);
let updateComponent = null;
if (update === 1) {
updateComponent = <UpdateComponent></UpdateComponent>;
}
return (
<div>
{ updateComponent }
</div>
)
}
sorry for bad example
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mamdasan |
