Reputation: 1462
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.
Upvotes: 0
Views: 78
Reputation: 521
You can pass the value to the parent component and set the state there.
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.
Upvotes: 1
Reputation: 501
<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);
}
Upvotes: 0
Reputation: 6015
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
}
Upvotes: 1