thechans7
thechans7

Reputation: 21

How to fix onSubmit function not showing state when button clicked?

I am having trouble with accessing the state on my component. I don't know if I am not assigning the state at all or if it has to do something with not binding and passing down props correctly.

When the user clicks "Add Student" a form renders, which it does. When the user then fills out the form and submits, I want to show an alert, but for some reason, I am not getting anything for my state values.

 constructor(props) {
    super(props);
    this.state = {
        studentName: '',
        studentId: '',
        isHidden: true
    }
}

 handleChange  = e => {
    this.setState({
        studentName: e.target.value,
        studentId: e.target.value2
    })
}


 handleSubmit = e => {
    e.preventDefault();
    alert("student name: " + this.state.studentName); 
}


 render() {
    return (
        <div>
            <Button
                variant="primary" 
                onClick={this.toggleHidden.bind(this)} 
                size="lg" active>
                Add Student
            </Button>
            {!this.state.isHidden && <Child handleSubmit={this.handleSubmit} />}
        </div>

    )
} 

const Child = props => {
return (
    <Form>
        <Form.Row>
            <Col>
                <Form.Control 
                name="studentName" 
                value ={props.studentName} 
                placeholder="Student name" 
                onChange={props.onChange}
                />
            </Col>
            <Col>
                <Form.Control 
                ...

                />
            </Col>
        </Form.Row>
        <Button
            onClick={props.handleSubmit}
            variant="primary" 
            type="submit">
            Submit
          </Button>
    </Form>
)
}

Upvotes: 0

Views: 196

Answers (1)

seanulus
seanulus

Reputation: 885

You need to pass your handleChange function down and this.state.studentName.

<Child handleSubmit={this.handleSubmit} onChange={this.handleChange} studentName={this.state.studentName}/>

Also, I would refactor your handleChange function to make it dynamic if you plan on changing multiple values in your form.

handleChange  = e => {
  this.setState({
    [e.target.name]: e.target.value,
  })
}

Upvotes: 1

Related Questions