Reputation: 95
I want to know is it possible to access the next or prev element in ReactJs?I have two inputs
by labels a
and b
.In handlerChecked
function I want to check the attribute checked
of both inputs.For example I checked a
and I want also to check b
was checked or not. How can I do it?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
.
.
.
}
}
.
.
.
handlerChecked = (e, elem) => {
let isChecked = e.target.checked
let value = e.target.value
let checknext = e.target.next('input').checked //In this part I want to check the attribute checked of other Input////
}
.
.
.
render() {
return (
<div>
<input type="checkbox" className="" value="0" onChange={this.handlerChecked} /> <label><span>a</span></label>
<input type="checkbox" className="" value="1" onChange={this.handlerChecked} /> <label><span>b</span></label>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('Result'))
Upvotes: 0
Views: 88
Reputation: 697
The short answer is no, React doesn't work that way, you can't go up and down an element's ancestor's tree to find sibling elements.
A common way to implement this feature is to give each checkbox a name
attribute.
For example:
<div>
<input name="check1" type="checkbox" onChange={this.handlerChecked} checked={this.state.check1} /> <label><span>a</span></label>
<input name="check2" type="checkbox" onChange={this.handlerChecked} checked={this.state.check2} /> <label><span>b</span></label>
</div>
handle these two checkboxes with one handler
const handlerChecked = (e) => {
const {name, checked} = e.target
this.setState({
[name]: checked
})
}
then in your state keep track of those 2 names like this:
this.state = {
check1: false,
check2: false
}
Upvotes: 3