Skip to content
Advertisement

Using react-router to redirect upon form submission

When I enter a search term (name, email, username) I want the page to filter out one card from all of the cards based on the search value. I think when the user presses enter, we would need to redirect to a new page to display the card.

I have the code for searchbar and the user component which would be responsible for displaying the single user card. Would we need to use the Redirect feature of the react-router to make this possible? I was struggling with how to implement it as props (the searchItem) also needs to be passed to the User component.

enter image description here

Searchbar.jsx

JavaScript

User.jsx

JavaScript

UserList.jsx

JavaScript

Advertisement

Answer

I don’t think you to need to use react-router here to achieve this.

The type of search you want determines the approach you can take. Do you want the cards to be filtered on each key press or only on form submit?

Currently you have a mix of these two approaches since you have a form element with an onSubmit, but you also have an input element with an onChange (uncontrolled and controlled).

Here’s a simplified example of a live search, controlled component approach:

JavaScript

For the uncontrolled approach the filter idea can stay untouched, but you remove the value and onChange props on the input and use your handleSubmit function to set the searchItem. To get the value of an input you need to use a ref using this approach. See this for more information.

sandbox example

Advertisement