0

I have defined a state called 'filter' in my application. The state is defined in the parent class. There are four buttons that have been defined with different values.

<button class="w-25 btn menu-btn" value='inbox' onClick={this.props.filterData}>Inbox</button>
<button class="w-25 btn menu-btn" value='rejected'  onClick={this.props.filterData}>Rejected</button>
<button class="w-25 btn menu-btn" value='accepted' onClick={this.props.filterData}>Accepted</button>
<button class="w-25 btn menu-btn" value='archive' onClick={this.props.filterData}>Archive</button>

I want to update filter state value according to the button value which is clicked.

4 Answers 4

2
filterData(e) {
  this.setState({ foo: e.target.value })
}
Sign up to request clarification or add additional context in comments.

Comments

1

In the parent component, implement a function that is passed down to the child under the prop filterData

filterData(event) {
   this.setState({ filter: event.target.value }) // since the state has key filter in your parent
}

Comments

1

You can pass the value to the parent component and set the state there.

View example.

It will look something like this:

class ParentComponent extends React.Component{
    state: { filter: '' }

    handleClick = (data) => {
        this.setState({filter: data});
    }

    render() {
         return (
                <div className="col-sm-9" >
                    <childComponent onClick={this.handleClick}/> 
                </div>
        )
     }
}
class childComponent extends React.Component{

    render() {
         return (
                <div className="col-sm-9" >
                    <button class="w-25 btn menu-btn" value='inbox' onClick={this.props.onClick(filterData)}>Inbox</button>
<button class="w-25 btn menu-btn" value='rejected'  onClick={this.props.onClick(filterData)}>Rejected</button>
<button class="w-25 btn menu-btn" value='accepted' onClick={this.props.onClick(filterData)}>Accepted</button>
<button class="w-25 btn menu-btn" value='archive' onClick={this.props.onClick(filterData)}>Archive</button>

                </div>
        )
     }
}

It's not tested, but conveys the idea.

Comments

0
<button class="w-25 btn menu-btn" value='inbox' onClick={this.filterData}>Inbox</button>


filterData = (event) => {

console.log(event.target.value);
}

You need to use event.target.value to get the button value or you can just pass the argument as shown below.

<button class="w-25 btn menu-btn" value='inbox' onClick={() => this.filterData('inbox')}>Inbox</button>

filterData = (value) => {

    console.log(value);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.