TransWikia.com

How do you pass props through react router?

Stack Overflow Asked by Aidan Paetsch on December 5, 2021

import React, { Component } from 'react';
import {
    Route,
    BrowserRouter as Router,
    Switch,
    Redirect
} from "react-router-dom";
import Landing from './Pages/Landing';
import FourInARow from "./Pages/fourinarow";
import logo from './logo.svg';
import './App.css';

function PublicRoute({ component: Component, mode, ...rest}){
    console.log(...rest)
    return (
        <Route
            {...rest}
            render={ (props) => mode !== null
                ? <Component {...rest} />
                : <Redirect to={'/fourinarow'}/>
            }
        />
    );
}


export default class App extends Component {
    constructor(){
        super();
        this.state = {
            mode: null
        }
    }
    setMode = (mode) => {
        this.setState({mode: mode});
        console.log('click');
    }

    render(){
        return (
            <div className="App">
                <Router>
                    <Switch>
                        <Route exact path='/'
                               render={(props) => <Landing setMode={this.setMode}/>}/>
                        <PublicRoute
                            path='/fourinarow'
                            component={FourInARow}
                            mode={this.state.mode}/>
                    </Switch>
                </Router>

            </div>
        );
    }
}

I am trying to pass props through my PublicRoute function with the hopes of later adding a privateRoute function that requires authentication. Both of these functions work as should for everything but passing props. The Route component is already working to pass props.

One Answer

One thing I see is in PublicRoute you are destructuring mode and ...rest out of props but you are not passing mode or props into Component.

Answered by EvanMorrison on December 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP