Search code examples
reactjsredux

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


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???


Solution

  • 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);