semantic ui react Setting dropdown value to state

Srikanth Gowda picture Srikanth Gowda · Mar 13, 2018 · Viewed 21.3k times · Source

how to have dropdowns selected value in state.here is my code iam getting value for name field but dropdown not working, can anyone find out what i am missing?

MyComponent.js

import React,{Component} from 'react';

class MyComponent extends Component{
state={
   data:{
       name:'',
       subject:''  
   }
}

 onChange = e =>
    this.setState({
        data: { ...this.state.data, [e.target.name]: e.target.value }
    },()=>{
        console.log(this.state.data);
    }
    )

render(){
const {data}=this.state;
const subjects= [
              {text: '1',value: 'kannada'},
              {text: '2', value: 'english'},
              {text: '3',value: 'hindhi'}
            ]
return(
<div>
            <Input 
             name="name"
             onChange={this.onChange} 
             placeholder='Your name ...' 
            />
            <Dropdown 
             placeholder='Select Subject'
             name="subject"
             onChange={this.onChange}
             selection 
             options={subjects} 
             />
</div>

)
}
}
export default MyComponent;

how to have selected dropdown value in state?, iam getting changed value for name field but for dropdown not getting.

Answer

Omar picture Omar · Mar 13, 2018
handleChange = (e, { value }) => this.setState({ value })

Add value prop to Dropdown

      render(
          const { value } = this.state;
        return(
         <Dropdown 
         placeholder='Select Subject'
         name="subject"
         onChange={this.handleChange}
         selection 
         options={subjects} 
         value={value}
         />)
       )