Pubudu Jayasanka
Pubudu Jayasanka

Reputation: 1462

How to read value field in button when it is clicked in react.js

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

Answers (4)

Hamza Ahmed
Hamza Ahmed

Reputation: 521

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.

Upvotes: 1

Lokesh Kumar Meena
Lokesh Kumar Meena

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

Dhananjai Pai
Dhananjai Pai

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

Modig
Modig

Reputation: 1036

filterData(e) {
  this.setState({ foo: e.target.value })
}

Upvotes: 2

Related Questions