I was trying to conditionally show/hide a set of input fields based on a button click event. If the button was clicked, the value of showExtraDetails div will be toggled between true and false.
Here's what I've tried:
state = {
ItemName: '',
ItemPrice:'',
ItemDate: '',
ItemPlace: '',
ItemType: '',
}
/*On hitting submit button, I'm logging the state and resetting the form fields after the state was stored in to newArray after appending*/
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state);
newArray = [...newArray, this.state];
console.log(newArray)
this.setState({
ItemName: '',
ItemPrice:'',
ItemDate: '',
ItemPlace: '',
ItemType: '',
})
}
/*When the input fields change, I'm updating the state*/
change =e =>{
// this.props.onChange({[e.target.name]:e.target.value})
this.setState({
[e.target.name]:e.target.value
})
}
/* toggling the showExtraDetails value after button was hit */
addExtraFoodDetails=() =>{
// e.preventDefault()
showExtraDetails = !showExtraDetails
console.log(showExtraDetails)
// e.preventDefault()
}
render(){
return(
<div>
<h5>Add Item</h5>
<form onSubmit={e => this.handleSubmit(e)}>
<input type="text" name="ItemName" placeholder="Enter the Item name"
value={this.state.ItemName}
onChange={e=> this.change(e)}
/>
<input type="number" name="ItemPrice" placeholder="Enter the item price"
value={this.state.ItemPrice}
onChange={e=>this.change(e)}
/>
<input type="date" name="ItemDate"
value={this.state.ItemDate}
onChange={e=>this.change(e)}
/>
<br/>
<input type="submit" name="submitItem" value="Save" />
</form>
<button onClick={this.addExtraDetails}>Add extra details</button>
<br/>
{showExtraDetails ?
(<div>
<input type="text" name="ItemPlace" value={this.state.ItemPlace}/>
<select name="ItemType" value={this.state.ItemType}>
<option value="none" disabled>--Select--</option>
<option value="type1">Type1</option>
<option value="type2">Type2</option>
<option value="type3">Type3</option>
<option value="others">Others</option>
</select>
</div>) : null
}
<br/>
<ul>
{newArray.map(item => <li>{item.ItemName}</li>)}
</ul>
</div>
)
}
But, when I hit the Add extra details button, I can only see the value of showExtraDetails as true/false after toggling, but the div is not getting updated with Showing/Hiding of the extra fields.
Am I missing something here? What is the best way to handle this?
I've seen in angular ngIf would do this. But I don't see such equivalent in React. I got some suggestions to make use of CSS styles by toggling the id's of the div. But I'm trying to apply something which is React specific.
Thanks.
showExtraDetailsdefined? You need to put it in your state if you want react to rerender when that value changes (usingsetStatenot direct assignment)