I'm creating a form and now attempting to do some input validation, and I'm struggling to grab the checked value from my radio component.
In one file I have:
<FormControl component="fieldset" name="method-of-payment">
<RadioGroup onChange={this.handleChange} >
<FormControlLabel value="credit" control={<Radio />} label="Credit Card"/>
<FormControlLabel value="check" control={<Radio />} label="Check"/>
<FormControlLabel value="purchase-order" control={<Radio />} label="Purchase Order"/>
</RadioGroup>
</FormControl>
And I'm trying to grab the value doing this in another file (it's worked for everything else):
this.setState({
method-of-payment: document.getElementsByName('method-of-payment')[0].value
})
But I'm having no luck getting the correct value.
I appreciate any help.
Edit: here's a link to the documentation I followed: https://material-ui.com/components/radio-buttons/
This looks like it's likely to be a bug-prone approach, and in general accessing elements directly is a React anti-pattern.
A better way would be to store the checked <Radio>
element value as a property in your state. Use the onChange
prop of your <RadioGroup>
to hook in to when the selection changes, store it in your state and use this in the value
prop of your containing <RadioGroup>
.
You should add an event listener and then update your state based on the value
you can get from the event. If you hook it up like that then you don't have to access the element to find its value - you already know it as it's in your state.
Basic example would go something like this:
class MyForm extends Component {
state = { selected: "credit" };
handleChange = ev => {
this.setState({ selected: ev.target.value });
};
render() {
const { selected } = this.state;
return (
<FormControl component="fieldset" name="method-of-payment">
<RadioGroup onChange={this.handleChange} value={selected}>
<FormControlLabel
value="credit"
control={<Radio />}
label="Credit Card"
/>
<FormControlLabel value="check" control={<Radio />} label="Check" />
<FormControlLabel
value="purchase-order"
control={<Radio />}
label="Purchase Order"
/>
</RadioGroup>
</FormControl>
);
}
}