Home > Mobile >  React Redirect with a parameter
React Redirect with a parameter

Time:11-01

I am working on a project. I want to preform a onClick method that redirect to another page and pass a parameter. But the Redirect method does not work even without pass the parameter. Could anyone take a look what is wrong with my code?

In my app.js, I have code to switch route:

<Router>
   <Switch>
        <Route path= "/Home">
           <Home/>
          </Route>
          <Route path= "/Projects">
           <Projects/>
          </Route>
          <Route path= "/Results">
           <Results/>
          </Route>
    </Switch>
 </Router>

In my component, I have:

function Search() {
  const [searchTerm, setTerm] = useState("");

  function handleChange(event) {
    setTerm(event.target.value);
  }

  function handleClick(event) {

  if (searchTerm.length > 0) {
    return(
 
      <Redirect
      to={{
        pathname: "/Results",
        state: {searchTerm}
      }}
    />
    
    );
  }

  event.preventDefault();
}


return (
  <div>
    <nav class="navbar navbar-light bg-light">
      <div class="container-fluid justify-content-end">
        <form class="d-flex">
          <input onChange={handleChange} value={searchTerm} class="form-control me-2" type="search" placeholder="Search" aria-label="Search" />
          <button onClick={handleClick} class="btn btn-outline-success">Search</button>
        </form>
      </div>
    </nav>
  </div>
);

}

CodePudding user response:

Redirect won't work if you return it from calling a function. If you want to get to /results page using Redirect you can create a new state:

const [redirect, setRedirect] = useState(false);

and set this state to true if the input value meets the required conditions searchTerm.length > 0. Then, you can use conditional rendering to add Redirect to your return statement

function handleClick() {

  if (searchTerm.length > 0) {
    setRedirect(true)
  }
}

return (
    <>
      {redirect && (
        <Redirect
          to={{
            pathname: "/Results"
          }}
        />
      )}
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <button onClick={handleClick}>Search</button>
    </>
  );

Working example with Redirect

The second way is to use hook useHistory():

const history = useHistory();

function handleClick() {

  if (searchTerm.length > 0) {
    history.push("/Results");
  }
}


Example with useHistory

CodePudding user response:

With a little change, your code works well.

Instead of using Redirect component (Route), You need to do a simple change route with history.push method in this way:

import {useHistory} from 'react-router-dom';

function Search() {
  const [searchTerm, setTerm] = useState("");

  function handleChange(event) {
    setTerm(event.target.value);
  }

  function handleClick(event) {
    if (searchTerm.length > 0) {
      history.push({
        pathname: '/Results',
        state: {searchTerm}
      })
    }
  }

  // rest of the codes ...
}

Now in your <Results/> component, you can consume this state:

import {useLocation} from 'react-router-dom';

function Results () {
  const location = useLocation();
  
  useEffect(() => {
    const searchTerm = location.state.searchTerm
    console.log(searchTerm)
  }, [])

  // rest of the codes ...

}
  • Related