Using react-router to redirect upon form submission

TanDev

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

import React, { useState } from "react";
import UserList from "./UserList";
import User from "./Components/User";
import { Link, Redirect } from "react-router-dom";

const SearchBar = () => {
  const [searchItem, setSearchItem] = useState("");

  const handleChange = (e) => {
    console.log(e.target.value);
    setSearchItem(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setSearchItem("");
  };

  return (
    <>
      <div className="searchbar">
        <form onSubmit={handleSubmit}>
          <input
            name="name"
            placeholder="Enter Name, Email or Username to Search"
            type="text"
            className="search"
            value={searchItem}
            onChange={handleChange}
          />
        </form>
      </div>
      <UserList />
    </>
  );
};

export default SearchBar;

User.jsx

import React from "react";
import Card from "./Card";

const User = (props) => {
  return (
    <Card
      key={props.id}
      name={props.name}
      email={props.email}
      website={props.website}
      phone={props.phone}
    />
  );
};

export default User;

UserList.jsx

import React, { useState, useEffect } from "react";
import Card from "./Components/Card";

const UserList = ({ searchItem }) => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((json) => {
        console.log(json);

        const newData = json.map((object) => ({
          id: object.id,
          email: object.email,
          website: object.website,
          phone: object.phone,
          name: object.name,
        }));

        // previousData is an empty array and the newData consists of all the users
        // using the spread operator, we copy the newData into the previousData
        setData((previousData) => [...previousData, ...newData]);
      });
  }, []);

  return (
    <>
      <div className="container">
        {data.map((info) => {
          return (
            <Card
              key={info.id}
              name={info.name}
              email={info.email}
              website={info.website}
              phone={info.phone}
            />
          );
        })}
      </div>
    </>
  );
};

export default UserList;
Bas van der Linden

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:

const User = (props) => {
  return <p>{props.name}</p>;
};

const UserList = ({ searchItem }) => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((json) => {
        console.log(json);

        const newData = json.map((object) => ({
          id: object.id,
          email: object.email,
          website: object.website,
          phone: object.phone,
          name: object.name,
        }));

        setData(newData);
      });
  }, []);

  const filteredUsers = data.filter((user) => {
    return user.name.includes(searchItem);
  });

  return filteredUsers.map((user) => {
    return <User key={user.id} name={user.name} />;
  });
};

const SearchBar = () => {
  const [searchItem, setSearchItem] = useState("");

  const handleChange = (e) => {
    console.log(e.target.value);
    setSearchItem(e.target.value);
  };

  return (
    <>
      <div className="searchbar">
        <form onSubmit={(e) => e.preventDefault()}>
          <input
            name="name"
            placeholder="Enter Name, Email or Username to Search"
            type="text"
            className="search"
            value={searchItem}
            onChange={handleChange}
          />
        </form>
      </div>
      <UserList searchItem={searchItem} />
    </>
  );
};

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Using react-router to redirect upon form submission

From Java

Redirect and refresh page on form submission in React frontend

From Dev

Clear an Angular form upon Submission

From Dev

Upon Redirect of Form Submission within iFrame jQuery Not Detecting Updated Src Attribute

From Dev

React router - redirect using indexRoute

From Dev

Values changing upon form submission (Dropdown form)

From Dev

React Router's match param appears and then disappears with form submission call

From Dev

Javascript: Appending form input into a table upon submission

From Dev

PHP Contact Form returning error upon submission

From Dev

Preventing page reload upon form submission to database

From Dev

Form Fails to Reset Upon Submission ReactJS Flux

From Dev

Redirect after AJAX form submission

From Dev

Cannot redirect after form submission

From Dev

How to redirect page on form submission

From Dev

redirect straight after form submission

From Dev

Redirect after AJAX form submission

From Dev

Redirect Url After Form Submission

From Dev

Orchard CMS Send Email to Multiple/Different Email Addresses Upon Form Submission Using Workflows

From Dev

React Form with file submission

From Dev

Redirect using react-router in redux middleware

From Dev

React Router redirect using alternate route configuration

From Dev

React Router (Dom) v4 redirect to different route upon input enter key press

From Java

Using React Router the <Redirect /> Does not redirect anywhere, but why?

From Dev

Upon login, it redirect me back to login form

From Dev

How to send and access a parameter/value upon Form Submission to next controller

From Dev

Angular.js: Set form fields "dirty" upon submission

From Dev

radio button value being sent as "on" upon form submission

From Dev

Animating invalid element's nearest divs upon form submission

From Dev

dowpdown should display the selected value upon submission of form

Related Related

  1. 1

    Using react-router to redirect upon form submission

  2. 2

    Redirect and refresh page on form submission in React frontend

  3. 3

    Clear an Angular form upon Submission

  4. 4

    Upon Redirect of Form Submission within iFrame jQuery Not Detecting Updated Src Attribute

  5. 5

    React router - redirect using indexRoute

  6. 6

    Values changing upon form submission (Dropdown form)

  7. 7

    React Router's match param appears and then disappears with form submission call

  8. 8

    Javascript: Appending form input into a table upon submission

  9. 9

    PHP Contact Form returning error upon submission

  10. 10

    Preventing page reload upon form submission to database

  11. 11

    Form Fails to Reset Upon Submission ReactJS Flux

  12. 12

    Redirect after AJAX form submission

  13. 13

    Cannot redirect after form submission

  14. 14

    How to redirect page on form submission

  15. 15

    redirect straight after form submission

  16. 16

    Redirect after AJAX form submission

  17. 17

    Redirect Url After Form Submission

  18. 18

    Orchard CMS Send Email to Multiple/Different Email Addresses Upon Form Submission Using Workflows

  19. 19

    React Form with file submission

  20. 20

    Redirect using react-router in redux middleware

  21. 21

    React Router redirect using alternate route configuration

  22. 22

    React Router (Dom) v4 redirect to different route upon input enter key press

  23. 23

    Using React Router the <Redirect /> Does not redirect anywhere, but why?

  24. 24

    Upon login, it redirect me back to login form

  25. 25

    How to send and access a parameter/value upon Form Submission to next controller

  26. 26

    Angular.js: Set form fields "dirty" upon submission

  27. 27

    radio button value being sent as "on" upon form submission

  28. 28

    Animating invalid element's nearest divs upon form submission

  29. 29

    dowpdown should display the selected value upon submission of form

HotTag

Archive