1

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.

1 Answer 1

2

you need setState's argument to be an object.

handleChange = (event) => {
    this.setState({ [event.target.username]: event.target.value });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.