I’m implementing the Wikipedia viewer project as a React exercise. I hit a point where I have to do a state update when I submit the search form.
Here’s a quick pen of the relevant parts: https://codepen.io/graycoatkev/pen/QOYKoV?editors=0010
There’s a main
App component with two child components
App keeps the search term in its state (since it will pass it down the
SearchResult), so I have to make a handler to update it when the form in the
SearchBox is submitted.
Now, since the event handler is attached to the
<form>, it’s what the
event object points to. I figured that a way to derive the search term in the textbox is by using
This works, but are there other ways of getting the value from the textbox? I tried
event.target.getElementById('search'), but the console says that it’s not a function. I think you can also keep a separate state for
SearchBox for the search term, but that means writing more code to update it as the value in the textbox changes (and also, there are gonna be two states for basically the same value, which doesn’t feel right).