Home > front end >  Redirecting in the new React_router-dom v6
Redirecting in the new React_router-dom v6

Time:02-27

I have just started react and using custom hooks and there is an issue in my page redirection

When the button is clicked it is supposed to take me to another page but as soon as i use the Navigate hook from react-router-dom it renders an empty page

This is my home.js

import * as React from 'react';

import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import ButtonBase from '@mui/material/ButtonBase';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';

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




//image button rendering
const images = [
  {
    url: 'https://images.pexels.com/photos/1251861/pexels-photo-1251861.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
    title: 'Student Login',
    width: '100%',
    path : '/student'
  },
  {
    url: 'https://images.pexels.com/photos/2173508/pexels-photo-2173508.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500',
    title: 'Staff Login',
    width: '100%',
    path : '/admin'
  },
];

const ImageButton = styled(ButtonBase)(({ theme }) => ({
  position: 'relative',
  height: 200,
  [theme.breakpoints.down('sm')]: {
    width: '100% !important', // Overrides inline-style
    height: 100,
  },
  '&:hover, &.Mui-focusVisible': {
    zIndex: 1,
    '& .MuiImageBackdrop-root': {
      opacity: 0.15,
    },
    '& .MuiImageMarked-root': {
      opacity: 0,
    },
    '& .MuiTypography-root': {
      border: '4px solid currentColor',
    },
  },
}));

const ImageSrc = styled('span')({
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  backgroundSize: 'cover',
  backgroundPosition: 'center 40%',
});

const Image = styled('span')(({ theme }) => ({
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  color: theme.palette.common.white,
}));

const ImageBackdrop = styled('span')(({ theme }) => ({
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  backgroundColor: theme.palette.common.black,
  opacity: 0.4,
  transition: theme.transitions.create('opacity'),
}));

const ImageMarked = styled('span')(({ theme }) => ({
  height: 3,
  width: 18,
  backgroundColor: theme.palette.common.white,
  position: 'absolute',
  bottom: -2,
  left: 'calc(50% - 9px)',
  transition: theme.transitions.create('opacity'),
}));

const Home = () => {
  //redirect function
  let navigate = useNavigate(); 
  const routeChange = () =>{  
    navigate('/admin/login');
  }

  return (
    <React.Fragment>
    
      <Grid
        container
        spacing={0}
        direction="column"
        alignItems="center"
        justifyContent="center"
        style={{ minHeight: '100vh' }}
      >
        <Grid item xs={3}>
          <Box sx={{ display: 'flex', flexWrap: 'wrap', minWidth: 400, width: '100%' }}>
            {images.map((image) => (
              <ImageButton
                focusRipple
                key={image.title}
                style={{
                  width: image.width,
                }}
                onClick={routeChange}

              >
                <ImageSrc style={{ backgroundImage: `url(${image.url})` }} />
                <ImageBackdrop className="MuiImageBackdrop-root" />
                <Image>
                  <Typography
                    component="span"
                    variant="subtitle1"
                    color="inherit"
                    sx={{
                      position: 'relative',
                      p: 4,
                      pt: 2,
                      pb: (theme) => `calc(${theme.spacing(1)}   6px)`,
                    }}
                  >
                    {image.title}
                    <ImageMarked className="MuiImageMarked-root" />
                  </Typography>
                </Image>
              </ImageButton>
            ))}
          </Box>

        </Grid>   
   
      </Grid> 
    </React.Fragment>
  );
       
    
};

export default Home;

This is redirect.js

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
// import { useContext } from 'react';

import { PrivateStudentRoute } from './PrivateStudentRoutes';
import { PrivateStaffRoute } from './PrivateStaffRoutes';
import { PublicRoute } from './PublicRoutes';

import Action_Page from '../../admin_page/.home/Action_Page';
import Home from '../home/Home';
import LoginStaff from '../home/staff/LoginStaff';
import LoginStudent from '../home/student/LoginStudent';

import React from 'react';


const user_routes = (
 
    
    <Switch>

        <PublicRoute path="/home" exact component={Home} />

        <PublicRoute path="/student/login" exact component={LoginStudent} />

        <PublicRoute path="/admin/login" exact component={LoginStaff} />

        <Route path="*" component={Home}/>

    </Switch>

);

const Redirect_page = () => {
    return (
        <Router>
            {user_routes}
        </Router>
    );
};

export default Redirect_page;

I think the error is in how the navigate function is defined in my code can someone. in redirect.js publicstudentroute and publicstaffroute is just route with proper authentication. page renders normally if i exclude routeChange function

CodePudding user response:

React-router v6 introduced Routes and elements, which replace Switch and component.

If you want to redirect user to another page, you need to adjust to these new features. Your user_routes should looke like this:

<Routes>

    <PublicRoute path="/home" exact element={<Home />} />

    <PublicRoute path="/student/login" exact element={<LoginStudent />} />

    <PublicRoute path="/admin/login" exact element={<LoginStaff />} />

    <Route path="*" element={<Home />}/>

</Routes>

You can read about upgrading from v5 to v6 here

  • Related