Rajesh Khadka
Rajesh Khadka

Reputation: 61

How can I handle the multiple select box in react in a single state

My initial State

const [state,setState] = useState({
country : "",
nationality : "",
})

My first select tag :

<select> //select for country
<option>Nepal<option/>
<option>USA<option/>
</select>

My second select tag :

<select> //select for nationality 
<option>Nepali<option/>
<option>Ameracain<option/>
</select>

At the end , I need all the selected values of both select tag in the single state.

const [state,setState] = useState({
    country : "Nepal",
    nationality : "Nepali",
    })

Upvotes: 1

Views: 1086

Answers (2)

Salah El bouhali
Salah El bouhali

Reputation: 26

You can use the name property and then use the multiple handle function in the React doc

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [state, setState] = useState({
    country: "Nepal",
    nationality: "Nepali"
  });
  const handleChange = (e) => {
    const {name,value}= e.target
 setState({...state,[name]:value})
    
  };
  return (
    <div className="App">
      <select name="country"  value={state.country} onChange={handleChange}>
        //select for country
        <option>Nepal</option>
        <option>USA</option>
      </select>
      My second select tag :
      <select name="nationality" value={state.nationality} onChange={handleChange}>
        //select for nationality
        <option>Nepali</option>
        <option>Americain</option>
      </select>
      {JSON.stringify(state)}
    </div>
  );
}

Upvotes: 1

Ahmad
Ahmad

Reputation: 884

here is a sample based on your example

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [state, setState] = useState({
    country: "Nepal",
    nationality: "Nepali"
  });
  const handleChange = (e) => {
    const copy = { ...state };
    switch (e.target.name) {
      case "country":
        copy.country = e.target.value;
        break;
      case "nationality":
        copy.nationality = e.target.value;
        break;
      default:
        break;
    }
    setState(copy);
  };
  return (
    <div className="App">
      <select name="country" onChange={handleChange}>
        //select for country
        <option>Nepal</option>
        <option>USA</option>
      </select>
      My second select tag :
      <select name="nationality" onChange={handleChange}>
        //select for nationality
        <option>Nepali</option>
        <option>Ameracain</option>
      </select>
      {JSON.stringify(state)}
    </div>
  );
}

Upvotes: 1

Related Questions