Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing value to parent component undefined

Im trying to pass a value from childComponent to parent component yet not successful.

childComponent.js

this.state{(
   val: 10
)}


handelClick(){
     let val = this.state.val
     this.props.useVal(val)
}

render(){
  return(
    <a onClick={() =>this.handelClick()}> click here</a>

)
}

parentComponent.js

this.state = {
   parentVal : ''
}

useVal(val){
    alert(val)
   this.setState({parentVal: val})
}


render(){
  return(
   <childComponent useVal={() => this.useVal} />
)
}

im getting undefined alert when I run it. How can I properly pass a value from child component to parent component?


1 Answers

You must pass along the argument passed to the useVal prop function.

<ChildComponent useVal={val => this.useVal(val)} />

Alternatively you can bind the useVal method to this in the constructor or make it into a class field arrow function so you don't have to create a new function in the render method.

class ParentComponent extends React.Component {
  state = {
    parentVal: ""
  };

  useVal = (val) => {
    alert(val);
    this.setState({ parentVal: val });
  }

  render() {
    return <ChildComponent useVal={this.useVal} />;
  }
}

class ParentComponent extends React.Component {
  state = {
    parentVal: ""
  };

  useVal = (val) => {
    alert(val);
    this.setState({ parentVal: val });
  }

  render() {
    return <ChildComponent useVal={this.useVal} />;
  }
}

class ChildComponent extends React.Component {
  state = {
    val: 10
  };

  handelClick = () => {
    let val = this.state.val;
    this.props.useVal(val);
  }

  render() {
    return <a onClick={this.handelClick}>click here</a>;
  }
}

ReactDOM.render(<ParentComponent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
like image 136
Tholle Avatar answered Dec 10 '25 01:12

Tholle



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!