My onChange is not working responsive

I followed this documentation and created a select tag with a response.
I edited this question: if I use className = "browser-default" in select it works fine. But for materializing select, it doesn't work.
onChange doesn't work in my case. The function is not called.

import React from 'react';

class Upload extends React.Component{
    constructor(props){
        super(props);
        this.state={
            degree:''
        }
        this.upload=this.upload.bind(this);
        this.degreeChange=this.degreeChange.bind(this);
    }
    componentDidMount() {
        $('select').material_select();
    }
    degreeChange(event){
        this.setState({degree:event.target.value});
        console.log(this.state.degree);
    }
    upload(){
        alert(this.state.degree);
    }
    render() {
        return (
            <div className="container">
            <form onSubmit={this.upload}>
                <div className="input-field col s4">
                        <select value={this.state.degree} onChange={this.degreeChange}>
                            <option value="" disabled>Choose Degree</option>
                            <option value="B.E">B.E</option>
                            <option value="B.Tech">B.Tech</option>
                        </select>
                </div>
                <div className="row center-align">
                    <input className="waves-effect waves-light btn centre-align" type="submit" value="Submit"/>
                </div>
            </form>
        </div>
        );
    }
}

      

I'm not wrong here, but my degreeChange function is not called. I don't understand what my mistake is.

0


source to share


1 answer


There is nothing wrong with the code. Are you sure it doesn't work? You might be assuming that the given state is synchronous when it is not. Try to register target.value

. you can also print the state value in the callback to your state.

degreeChange(event){
    console.log(`event value is ${event.target.value}`);
    this.setState({degree:event.target.value}, () => {
        console.log(this.state.degree);
    });
}

      



Script your exact code try changing the element around. you will see the state seems to be lagging behind. because the moment you print this state has not completed the render loop and the state has not been updated.

Screenshot of my changes

0


source







All Articles