Reputation: 427
I created radio button with 3 radios: I want to have lime as default checked radio button, I set lime as default value but it didn't work.
here is my code And I don't know how to solve my problem.
import React, {Component} from 'react';
class App extends Component{
constructor(props){
super(props)
this.handleflavorSubmit = this.handleflavorSubmit.bind(this)
this.onChangeRadio = this.onChangeRadio.bind(this)
this.state = {value : 'lime'};
}
onChangeRadio(e){
this.setState({value : e.target.value})
}
handleflavorSubmit(e){
alert("your favorite flavor is " + this.state.value)
e.preventDefault();
}
render(){
return(
<div>
<h1>Choose your flavor:</h1>
<form onSubmit = {this.handleflavorSubmit}>
<input type="radio" checked = {this.state.value === 'grapefruit'} onChange = {this.onChangeRadio} value= "grapefruit"/>Grapefruit
<input type = "radio" checked = {this.state.value === 'lime'} onChange = {this.onChangeRadio} value = "lime"/>Lime
<input type = "radio" checked = {this.state.value === 'orange'} onChange = {this.onChangeRadio} value = "orange"/>Orange
<input type = "submit" value = "submit"/>
</form>
</div>
)
}
}
export default App
Upvotes: 5
Views: 16137
Reputation: 1228
Your code is actually working. You just need to include paranthesis after the return.
Try it out in CodeSandbox. Here is the working code: https://codesandbox.io/s/red-rain-r81n4
import React,{Component} from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component{
constructor(){
super()
this.handleflavorSubmit = this.handleflavorSubmit.bind(this)
this.onChangeRadio = this.onChangeRadio.bind(this)
this.state = {value : 'lime'};
}
onChangeRadio(e){
this.setState({value : e.target.value})
}
handleflavorSubmit(e){
alert("your favorite flavor is " + this.state.value)
e.preventDefault();
}
render(){
return (
<div>
<h1>Choose your flavor:</h1>
<form onSubmit = {this.handleflavorSubmit}>
<input type="radio" checked = {this.state.value === 'grapefruit'} onChange = {this.onChangeRadio} value= "grapefruit"/>Grapefruit
<input type = "radio" checked = {this.state.value === 'lime'} onChange = {this.onChangeRadio} value = "lime"/>Lime
<input type = "radio" checked = {this.state.value === 'orange'} onChange = {this.onChangeRadio} value = "orange"/>Orange
<input type = "submit" value = "submit"/>
</form>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App/>, rootElement);
Upvotes: 3
Reputation: 2938
Add defaultChecked
property for the input
radio that you want to set as checked on it's first mount.
<input type = "radio" defaultChecked checked = {this.state.value === 'lime'} onChange = {this.onChangeRadio} value = "lime"/>Lime
Upvotes: 2