pmiranda
pmiranda

Reputation: 8420

React, pass data from child to parent with props

I have two components:

In a parent component:

handleSubmit= (val) => {
    console.log(val)//hello
    console.log("but I also needs the value of indexTab here, I just have the parameter val")
    console.log(indexTab) <---
}

render() {
    const val =" hello"

    return(
        <Child
            handleOnSubmit = {() => this.handleSubmit(val)}
            etc...

In Child I have:

class Child extends Component<Props> {

  render() {

    const { indexTab } = this.props;

    return (<Button onClick={handleSubmit}> {indexTab !== 2 ? "Save 0 or 1" : "Save 2"} </Button>
    );
  }
}

I need to use in the father the value of indexTab in handleSubmitSaveConfigurationsPre how can I pass that value with the props onClick={handleSubmit} ?

Upvotes: 0

Views: 215

Answers (3)

Dupocas
Dupocas

Reputation: 21297

To pass an aditional parameter to handleSubmit first you need to change the function's signature

handleSubmit= (val, foo) => {
    console.log(val)//hello
    console.log(foo)
}

Now prepare the callback pass to your Child to expect an aditional parameter

return <Child callback={foo => this.handleSubmit(val, foo)} />

And from inside Child call your callback

callback('foo')

Upvotes: 0

kooskoos
kooskoos

Reputation: 4859

Call handleSubmit wrapped inside an anonymous function with indexTab as argument.

<Button onClick={() => handleOnSubmit(indexTab)}>

Parent component

<Child
            handleOnSubmit = {(indexTab) => this.handleSubmit(val, indexTab)}
            etc...

Upvotes: 1

Gaspar Teixeira
Gaspar Teixeira

Reputation: 1267

In the parent you should do something like.

class Parent extends React.Component {
state = {
   tabIndex: null
}

handleSubmitSaveConfigurationsPre = val => {
    console.log(val);
    console.log(this.state.tabIndex);
}

setValuleFromChild = value => {
  this.setState({tabIndex: value });
}

<Child handleOnSubmit={this.setValuleFromChild} ...

in the children you should do something like:

render() {

    const { indexTab,  handleSubmit} = this.props;

    return (<Button onClick={() => handleSubmit(indexTab)}> {indexTab !== 2 ? "Save 0 or 1" : "Save 2"} </Button>
    );

Upvotes: 1

Related Questions