Issue
I am working on Reactjs and using nextjs, Right now i am trying to get value of "textarea" and "dropdown/select", but i am getting empty result,How can i do this ? I tried with following code
const msgChange = (e) => {
const value = e.target.value;
setState({
...state,
[e.target.msg]: value
});
};
const countryChange = (e) => {
const value = e.target.value;
setState({
...state,
[e.target.country]: value
});
};
const handleSubmit = (e) => {
var msg = state.msg;
alert('msg is '+msg);
}
<form className='row' onSubmit={handleSubmit}>
<select className="form-select" aria-label="Default select example" onChange={countryChange} name="country">
<option selected>Country</option>
<option value="abc">abc</option>
<option value="xyz">xyz</option>
</select>
<textarea onChange={msgChange} name="msgs"></textarea>
<input type="submit" value="send" className='sendbtn' />
</form>
Solution
You are setting the wrong attributes in the onChange
handlers for both the textArea
and select
dropdown.
Assuming you have the below kind of useState
in your code.
const [state, setState] = useState({});
You should use the below attributes to add your value to the state.
const msgChange = (e) => { const value = e.target.value; setState({ ...state, [e.target.name]: value }); }; const countryChange = (e) => { const value = e.target.value; setState({ ...state, [e.target.name]: value }); };
Access the value below from the state
const handleSubmit = (e) => { const msg = state.msgs; const country = state.country; console.log("message ---->", msg, "country --->", country); };
Answered By - Rohit Khandelwal
Answer Checked By - - Mildred Charles (ReactFix Admin)