I need heeeeeelp. I’m fairly new to React. I’m trying to make it so that the user submits input and when enter is hit, it displays that information. I’ve tried a billion things and I’m just kind of lost. In the handleSubmit() method, if I place the event.preventDefault() before what I want the code to do, nothing happens upon hitting enter/hitting submit. If I put it after, the page just refreshes back to the original. I’ve googled and googled and I just feel lost. Any help is appreciated. Thanks. My code (it’s not perfect, and right now I’m just trying to get this one thing to work before working on other things/the styling):
I don’t understand why you want to return an h1 from a submit event. Care to explain your thought process?
Anyway if you want to print in an h1 only after an event, you can simply link its visibility to a state variable.
In this case I’m adding a isVisible boolean to the component state to decide weather or not render the h1.
// add a visibility boolean in your state:
this.state = {
currentItem: '',
isVisible: false,
}
// on submit update the visibility
handleSubmit(event) {
event.preventDefault();
this.setState({
isVisible: !this.state.isVisible
})
}
// then render the h1 only if visible is true
return(
<form>[...]</form>
{this.state.isVisible &&
<h1>{this.state.currentItem}</h1>
}
)
It’s a grocery list, so every time something is added to the list via input from the user, I want it to be displayed.
It also probably won’t be an <h1> eventually, right now I just wanted it to actually display and then move on from there.
It does actually, thank you. The only problem is this doesn’t help with my input issue. The user needs to type in their list, but when I type something in the input field and hit enter/submit, it just refreshes. Unless I’m misreading your comment.