0

After submitting this form I want to be able to redirect the user to the next page (posts page).

However I tried by creating a <button onClick={() => <Redirect to="/posts" />} but seems not to work. Days ago it worked just fine for me but now I don't know what I'm missing...

This is the current file where I'm submitting a form and want the user to be redirected after submitting it

Auth.js

import React, { useState } from 'react'
import { actions } from './sagaSlice';
import { connect } from 'react-redux';
import { BrowserRouter as Redirect } from "react-router-dom";

const Auth = (props) => {
    const [formData, setFormData] = useState({
        username: '',
        email: '',
        password: ''
    });

    const handleFormData = e =>
        setFormData({
            ...formData,
            [e.target.name]: e.target.value
        });

    const { username, email, password } = formData;

    const handleSubmit = e => {
        e.preventDefault();
        props.login({
            username,
            email,
            password
        });
    }

    return (
        <div>
            <form
                onSubmit={handleSubmit}
            >
                <input
                    type="text"
                    name="username"
                    placeholder="Username"
                    onChange={handleFormData}
                    value={username}
                />
                <input
                    type="email"
                    name="email"
                    placeholder="Email"
                    onChange={handleFormData}
                    value={email}
                />
                <input
                    type="password"
                    name="password"
                    placeholder="Password"
                    onChange={handleFormData} value={password} />
                <button
                    type="submit"
                    onClick={() => <Redirect to="/posts" />}
                >
                    Login
                </button>
            </form>
            <button onClick={() => <Redirect to="/posts" />}>Go to posts</button>
        </div>
    );
}

const mapToProps = (state, ownProps) => {
    return ({
        user: state.user
    })
}

export default connect(mapToProps, actions)(Auth);

And my App.js file

App.js

import React from 'react';
import { connect } from 'react-redux';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import Auth from '../Auth/Auth';
import PostsView from '../PostsView/PostsView';
import PostViewSingle from '../PostViewSingle/PostViewSingle';

const App = (props) => {
    return (
        <div className="container">
            <Router>
                <Switch>
                    <Route path="/login" component={Auth} />
                    <Route path="/posts" component={PostsView} />
                    <Route path="/post/:id" component={PostViewSingle} />
                </Switch>
            </Router>
        </div>

    );
}

const mapToProps = (state) => {
    return ({
        isAuthenticated: state.user.isAuthenticated
    })
}

export default connect(mapToProps, null)(App);
Andres Urdaneta
  • 431
  • 4
  • 15
  • 1
    It never works like that. You can't return JSX from a button click. You have two options. 1. with the click, you can set a state and conditionally render `Redirect` component. 2. Instead of `Redirect` you can use `() => history.push("/posts")` – devserkan Jun 28 '20 at 23:12
  • Does this answer your question? [Programmatically navigate using react router](https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router) – devserkan Jun 28 '20 at 23:14
  • @devserkan the `() => history.push("/posts")` does the trick but when it redirects to the `/posts` route it doesn't fetch, or render anything on the screen – Andres Urdaneta Jun 28 '20 at 23:20
  • @devserkan after messing around with the `history.push` came up with the solution. Just had to add that line in the submitHandler instead of doing it on the `onClick` of the submit button – Andres Urdaneta Jun 28 '20 at 23:29

1 Answers1

1

It's hard to say for sure what's wrong without a minimal example of some sort. That being said there's a few things that might help you out:

  • You're (probably) incorrectly importing the Redirect component (you import BrowserRouter as Redirect). That should (again, probably) be changed to import { Redirect } from "react-router-dom";, assuming you still need the Redirect component.

  • You want to redirect a user after submitting the form. Therefore, your redirect logic should be in your handleSubmit callback. From there you can handle the redirect.

Here's an updated version of your Auth component:

import { Link, Redirect } from "react-router-dom";

const Auth = (props) => {
    const [formData, setFormData] = useState({
        username: '',
        email: '',
        password: ''
    });

    const handleFormData = e =>
        setFormData({
            ...formData,
            [e.target.name]: e.target.value
        });

    const { username, email, password } = formData;

    const handleSubmit = e => {
        e.preventDefault();
        props.login({
            username,
            email,
            password
        });
        
        // Perhaps also check if login was successful?
        history.push("/posts");
    }

    return (
        <div>
            <form
                onSubmit={handleSubmit}
            >
                <input
                    type="text"
                    name="username"
                    placeholder="Username"
                    onChange={handleFormData}
                    value={username}
                />
                <input
                    type="email"
                    name="email"
                    placeholder="Email"
                    onChange={handleFormData}
                    value={email}
                />
                <input
                    type="password"
                    name="password"
                    placeholder="Password"
                    onChange={handleFormData} value={password} />
                <button type="submit">
                    Login
                </button>
            </form>
            <Link to="/posts">Go to posts</Link>
        </div>
    );
}
Sam Gomena
  • 1,450
  • 11
  • 21