Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass props of one child component to another child component using parent component

Tags:

reactjs

redux

enter image description here

  1. I want to call a function in Second Child like

const CallListRow = (props) => {
    return (
        <TableRow key={props.id}>
            <TableRowColumn>{props.id}</TableRowColumn>
            <TableRowColumn>{props.date}</TableRowColumn>
            <TableRowColumn>{props.callerId}</TableRowColumn>
            <TableRowColumn><Link label="Click to Call" to="javascript:void(0)" onClick={()=>dialPhone(props.phone)}  >{props.phone}</Link></TableRowColumn>
            <TableRowColumn>{props.duration}</TableRowColumn>
        </TableRow>
    );
}
  1. And after onClick props.phone value want to get in First Child component

  2. Both child components are imported in Parent component.

  3. Then how to got clicked value in First Child component???

like image 380
Pankaj Avatar asked Nov 28 '25 11:11

Pankaj


1 Answers

You need to call a parent function that updates a state in the parent and then pass it as a prop to the First Child

Parent

..
changeSelected = (val) => {
     this.setState({selected: val})
}

render() {
  return (
     <div>
     <Firstchild selected={this.state.selected}/>
     <Secondchild changeSelected = {(val)=> {this.changeSelected(val)}}/>
     </div>
  )
}

FirstChild:

render() {
    console.log(this.props.selected);
}

SecondChild:

handleClick = (val) => {
    this.props.changeSelected(val);
}

Update with functional components :

Parent

const [selected, setSelected] = useState()
    
  ...

return (
  <div>
    <Firstchild selected={selected}/>
    <Secondchild changeSelected = {setSelected}/>
  </div>
 )
}

FirstChild:

useEffect(() => console.log(selected), [selected]);

SecondChild:

handleClick = (val) => changeSelected(val);
like image 82
Shubham Khatri Avatar answered Dec 01 '25 01:12

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!