user3362908
user3362908

Reputation: 443

ReactJS : Form Data Capture : values not setting properly

I am trying out with a small react app, with a form based data capture, after keying in the values, when user clicks submit button, values need to be captured in state variable. But, state variable contains null value in handleSubmit function. For clarity, code snippets are given below,

Constructor code, for the sake of completeness/clarity,

constructor(props)
{
    super(props);
    this.state = { 
        username : '', 
    };
}

handleChange function is where I set state variable,

handleChange = (event) => {
    this.setState( [event.target.username]: event.target.value );
}

handleSubmit function is where, I print state variable, which contains null value, instead of user inputted value.

handleSubmit = () => {
    console.log(this.state.username);
}

Component's render function is given below, which invokes handleChange and handleSubmit.

render() {
return(
    <div>
    <form>
    <label>
        Title:
        <input 
            type = "text"
            name="username" 
            onChange={event => this.handleChange(event)}/>
    </label>
            <button 
            label="Submit" 
            onClick={this.handleSubmit}>
            Submit
    </button>
    </form>
        </div>
)};

I am missing on something. I am new to react. Kindly advise.

Upvotes: 1

Views: 43

Answers (1)

markb
markb

Reputation: 279

you need setState's argument to be an object.

handleChange = (event) => {
    this.setState({ [event.target.username]: event.target.value });
}

Upvotes: 2

Related Questions