Reputation: 620
I'm building a React Component. This is a form, with a radio button, which can only be set to True and then no longer set back to false. I would like to be able to turn it on and off. And because worth read out.
What could the corresponding code look like?
At the moment I have that:
import React, { Component } from 'react';
class Form extends Component {
art = {
selected: "uppper"
}
onChange() {
console.log("Click")
}
render() {
return (
<form onSubmit={this.handleFormSubmit}>
<div>
<label>
<input type="radio" value="option1"
onClick={this.onChange} />
option1
</label>
</div>
<input type="submit" value="Submit" />
</form>
);
}
}
export default Form;
Upvotes: 0
Views: 7570
Reputation: 15688
while being consistent with using a class-component, your code would look something like this:
class Form extends Component {
state = {
selected: false
};
onChange = () => {
this.setState({
selected: !this.state.selected
});
};
render() {
return (
<form onSubmit={this.handleFormSubmit}>
<div>
<label>
<input
type="radio"
value="option1"
onClick={this.onChange}
checked={this.state.selected}
/>
option1
</label>
</div>
<input type="submit" value="Submit" />
</form>
);
}
}
export default Form;
Essentially what you need are 3 things.
onChange
handler to toggle the state value. Also ensure
that the onChange
handler is bound to the execution context by using
an arrow function or binding the this keyword.See working sandbox: https://codesandbox.io/s/mystifying-borg-gwl2q
Upvotes: 1
Reputation: 17239
Here's how you can do this:
import React, { useState } from 'react';
import { render } from 'react-dom';
const App = () => {
const [radioState, setRadioState] = useState(false);
const handleChange = () => {
setRadioState(!radioState)
}
return (
<input type="radio" checked={radioState} onClick={handleChange}/>
)
}
render(<App />, document.getElementById('root'));
Live example here.
Upvotes: 0