J.doe
J.doe

Reputation: 145

Redirect after enter form react

I have a form in react, actually I can make it work with a submit button. When I click on the submit button, a Link send me to the desired component.

But when I press "enter" after writing something in my input form, like most people do, nothing happen indeed.

How can I redirect to the results page when someone write something in the form and press enter key?

Here is the form, and his functional component with useState:


function Header(){

    const [title, setTitle] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        if (!title) return;
        setTitle(title);
        setTitle("");
        console.log(title);
    }

    return(
        <nav>
            <li className="liensNav">
                <Link className="lien" to="/">
                    {/* Tu as fill white dans le logo svg */}
                    <img className="logo" src={logo} alt="logo"></img>
                </Link>
            </li>
            <li className="liensNav">
                <Link className="lien" to="/">Top Games</Link>
            </li>
            <li className="liensNav">
                <Link className="lien" to="/top-streams">Top Live Streams</Link>
            </li>
            <li className="liensNav">

                <form className="formSubmit" onSubmit={handleSubmit}>

                    <input className="inputRecherche" type="text" value={title}
                    required onChange={(e) => setTitle(e.target.value)} />


                <button type="submit">
                    <Link
                    to={{
                        pathname: "/resultats",
                        state: {
                            id : title
                        }
                    }}
                    >
                        <img className="logoLoupe" src={search} alt="icone loupe"/>
                    </Link>
                </button>


                </form>

            </li>

        </nav>
    )
}
export default Header;

Maybe I need to use onKeyPress ? But anyway I don't know how to redirect on enter, that is the major problem.

Thanks if someone if passing by.

Upvotes: 1

Views: 2033

Answers (2)

tim
tim

Reputation: 727

You can just check if a specific value exists, if so then redirect.

if(title) {
  // redirect or whatever....
}

React-router-dom has a nifty redirect component.

Upvotes: 0

ibtsam
ibtsam

Reputation: 1720

Yes you would need onKeyPress or onKeyUp, in its handler you can check for enter like this and use history to redirect to the page

handleKeyDown(e) {
 if (e.key === 'Enter') {
  history.push('/resultats')
 }
}

you input

<input className="inputRecherche" type="text" value={title}
                onKeyPress={(e) => this.handleKeyDown(e)}
                required onChange={(e) => setTitle(e.target.value)} />

Hope it helps

Upvotes: 2

Related Questions