Jafrul Hossain
Jafrul Hossain

Reputation: 9

Input field still holds the data

I am new at react. I have a child component and there I have an input field in a modal. I have the state in parent component. After value submission the value still stays in the input. How can I overcome this problem?

This is my state and handler in parent class :

state = {
        unitName: ''
    }

    inuptChangeHandler = (event) => {
        event.preventDefault();
        this.setState({ [event.target.name]: event.target.value })
    }
postUnitHandler = () => {
        let unit = {
            unitName : this.state.unitName
        }
        Axios.post('http://localhost:4000/addUnit',unit).then(response => {
            console.log("unit added")

        }).catch(err => {
            console.log(err);
        })
        this.setState({ unitName: ''})

    }

Usage of child component:

 <AddUnit changeInput={this.inuptChangeHandler}
           addUnit={this.postUnitHandler} />

Child component

<div className="modal-body">
<form>
<div className="form-group">
<label className="text-dark" htmlFor="unit"><strong>Add Unit</strong></label>
<input type="text"  className="form-control" name="unitName"  onChange={props.changeInput} placeholder="Enter New Unit" />
</div>
</form>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" className="btn btn-primary" data-dismiss="modal" onClick={props.addUnit}>Save changes</button>
</div>

Each time I press submit, the input field should empty

Upvotes: 0

Views: 66

Answers (1)

Ahmed Waqas
Ahmed Waqas

Reputation: 255

pass the prop unitName to child component and then in input tag use value={unitName}

<input type="text"  className="form-control" name="unitName"  value={unitName} onChange={props.changeInput} placeholder="Enter New Unit" />

unitName should be a state in parent component which should be passed to child

Upvotes: 2

Related Questions