Send custom property to Privateroute component in React

Asked

Viewed 73 times

0

Problem:

Basic information: React project with the following dependencies.:

  "dependencies": {
    "@emotion/core": "^10.0.35",
    "@fortawesome/fontawesome-free": "^5.14.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.30",
    "@fortawesome/free-solid-svg-icons": "^5.14.0",
    "@fortawesome/react-fontawesome": "^0.1.11",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "alertifyjs": "^1.13.1",
    "bootstrap": "^4.5.0",
    "jquery-slim": "^3.0.0",
    "moment": "^2.27.0",
    "moment-timezone": "^0.5.31",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-bootstrap-table-next": "^4.0.3",
    "react-bootstrap-table2-paginator": "^2.1.2",
    "react-bootstrap-table2-toolkit": "^2.1.3",
    "react-datepicker": "^3.1.3",
    "react-dom": "^16.13.1",
    "react-flip-move": "^3.0.4",
    "react-images-viewer": "^1.6.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^3.4.3",
    "react-select": "^3.1.0",
    "react-spinners": "^0.9.0",
    "react-toggle-component": "^3.0.8",
    "reactstrap": "^8.5.1",
    "rxjs": "^6.6.3",
    "styled-components": "^5.2.0",
    "vanilla-masker": "^1.2.0"
  },

In the application I’m working on, in the file where I specify for the routes. App.js

I’m having trouble getting the property roles into the protected component that I’m creating. The component with the name Privateroute

Specifically on this tag Privateroute Code Line 34 below.:

import React from 'react';
import './Assets/FontawsomeIcons/FontawsomeIcons';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Header from './Components/Header/Header'
import Sidebar from './Components/Sidebar/Sidebar'
import { PrivateRoute } from './Components/Routes/PrivateRoute';
import Revenda from './Pages/Revenda/revenda';
import ListRevenda from './Pages/Revenda/ListRevenda.js';
import Usuarios from './Pages/Usuarios/Usuario';
import Manuais from './Pages/Manuais/Manuais';
import Home from './Pages/Home';
import ListManuais from './Pages/Manuais/ListManuais';
import Garantia from './Pages/Garantia/Garantia';
import ListGarantia from './Pages/Garantia/ListGarantia';
import {_LevelRoles} from './Config.js'; 

function App() {
    return (
        <Router>
            <div className="wrapper">
                {/* <!-- Sidebar  --> */}

                <Sidebar></Sidebar>

                {/* <!-- Page Content  --> */}
                <div id="content">
                    <Header></Header>
                    <div className="container-fluid">
                        <section name='content'>
                            <Switch>
                                <Route path='/Home' exact component={Home} />                              

                                {/* aqui pretendo enviar a propriedade roles */}
                                <PrivateRoute path='/revenda' exact component={ListRevenda} roles={[_LevelRoles.UsrRevenda]} />
                                <Route path='/revenda/tab/:tabName' exact component={ListRevenda}></Route>
                                <Route path='/revenda/new' exact key='add-revenda' component={Revenda}></Route>
                                <Route path='/revenda/:idRevenda' exact key='edit-revenda' component={Revenda}></Route>
                                <Route path='/revenda/:idRevenda/tab/:tabName' exact component={Revenda}></Route>
                                <Route path='/revenda/:idRevenda/addmanuais' exact component={Manuais}></Route>
                                <Route path='/revenda/:idRevenda/listmanuais' exact component={ListManuais}></Route>

                                <Route path='/garantia' exact component={ListGarantia}></Route>
                                <Route path='/garantia/tab/:tabName' exact component={ListGarantia}></Route>
                                <Route path='/garantia/new' exact key={'add-garantia'} component={Garantia}></Route>
                                <Route path='/garantia/:idGarantia' exact key='edit-garantia' component={Garantia}></Route>

                                <Route path='/usuario/:id' exact component={Usuarios}></Route>

                            </Switch>
                        </section>
                    </div>
                </div>
            </div>
        </Router>

    );
}

export default App;

then the protected component code

  import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { authenticationService } from '../../Services/AuthService';

export const PrivateRoute = ({ component: Component, roles ,  ...rest }) => (

   

    <Route  {...rest} render={props => {

        
        const currentUser = authenticationService.currentUserValue;

        debugger; 
        if (!currentUser) {
            debugger; 

           
            //não está logado, redirecione para a página de login com o url de retorno
            
            return  <Redirect to={{ pathname: '/Login', state: { from: props.location } }} />
           
        }
          


        // autorizado, retorna o component
        return <Component {...props} />
    }} />
)

i can’t see the property roles within props. There’s something wrong with the code?

  • He’s already given a console. roles?

  • or here ({ component: Component, roles , ...rest }) if it does so: (props) and just below gives a console.log(props)

  • using the props as follows as was your suggestion.: console.log(props); console.log(roles); roles this as Undefined and props does not show the roles property I still could not receive the property in the component.

2 answers

1

You can enter the roles directly on the Privateroute:

return <Component {...props} roles={roles} />

I’ve made adaptations for the code to work here, so make the modifications that are necessary.

Gist

  • Hello Renato Siqueira, it worked for me your suggestion. by changing the Privateroute component

0

Hi Breno, using render props does not solve your problem? Because React Router does not pass props, it ignores them by default. Instead of

<PrivateRoute path='/revenda' exact component={ListRevenda} roles={[_LevelRoles.UsrRevenda]} />

trial:

<PrivateRoute path='/revenda' exact
    render={(props) => (
          <ListRevenda  roles={[_LevelRoles.UsrRevenda]} />
    )} 
  • Sidnei Glasman, I tried as suggested with just an adjustment at the closing of the tag called Privaroute tried as follows: <Privateroute path='/reseller' Exact render={(props) => ( <Listrevenda roles={[_Levelroles.Usrrevenda]} /> )} /> haven’t been successful yet... roles arrives as Ufined and in props I couldn’t access the roles property

  • Pity, but anyway you solved the problem. I’m busy but still want to try more, this way I posted. I edited, because I had not seen that you had already solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.