Using react-router-dom with an input

Viewed 129

I want to redirect to use react-router-dom to re render what I write into my input when I submit, but I don't know how.

This is my input:

<form
    action="#"
    onSubmit={(e) => {
        e.preventDefault();
        dispatch(pokemonToSearch(value.toLowerCase()));
        setValue("");
    }}
>
    <div>
        <input
            value={value}
            type="text"
            onChange={(e) => setValue(e.target.value)}
        />
        <button type="submit">Search</button>
    </div>
</form>

I have a simple list, when I click one item, it renders the pokemon I clicked, that's works. But I want the same to happen when I search for one.

My searchbar is above my list, like this:

<SearchBar />
    <div className="container px-4 ">
        <Switch>
            <Route exact path="/">
                <PokemonList />
                <ViewMore />
            </Route>
            <Route exact path="/pokemon/:nameLink">
                <Pokemon />
            </Route>
        </Switch>
    </div>

I use a useEffect to fetch the specific data:

useEffect(() => {
    dispatch(getPokemonData(nameLink));
}, [dispatch, nameLink]);
1 Answers

Nevermind, I just solved it. What I did:

First imported useHistory:

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

Then created a constant with it:

const history = useHistory();

Then push the url I want onSubmit:

<form
    onSubmit={(e) => {
        e.preventDefault();
        dispatch(pokemonToSearch(value.toLowerCase()));
        history.push(`/pokemon/${value}`); // this right here
        setValue("");
    }}
>
</form>
Related