Home > Software design >  Unable to change dropdown value using Reactjs
Unable to change dropdown value using Reactjs

Time:12-14

I am working on Reactjs/Nextjs and right now i am trying to change dropdown value (working on update module) but right now i cant change droddown value,How can i do this ?I tried with following code

const Post =  function(props) {
    const [content2, setContent2] = useState('');
    }

useEffect(()=>{
    setContent2(post?.cat_name);
},[])

 <select value={post?.cat_name} className="form-control" name="cat_name" id="cat_name" onChange={(con2) => 
    {
        setContent2(con2);
    }}>
                          
 <option value="">Select Category</option>
    <option value="pined"  >Pined</option>
 </select>

CodePudding user response:

In your code, you are not updating the value of the select element correctly. The value attribute of the select element should be set to the current value of the content2 state's variable, like this:

value={content2}

and use the onChange event handler to update the value when the user selects a different option.

onChange={(event) => setContent2(event.target.value)}

CodePudding user response:

use content2 as value

value={content2}

CodePudding user response:

you can initialize content2 in declaration

 const [content2, setContent2] = useState(post? post.cat_name : "");

then the value attribute in select should be content2 also in onChange try to use event

<select 
value={content2} 
className="form-control" 
name="cat_name" 
id="cat_name" 
onChange={(event) => 
{
    setContent2(event.target.value);
}}>
<option value="">Select Category</option>
<option value="pined"  >Pined</option>
</select>
                      
  • Related