'How to do a redirection of a page to a route
indeed I would like to make a redirection of the different part lists (treenode.js) to the part information page which is called (PartItem.js1:https://i.stack.imgur.com/GU0tk.png
here is the code of the tree of pieces
/** @jsxImportSource @emotion/react */
// import React from "react";
import ReactDOM from "react-dom";
import { css } from '@emotion/react';
import NomenclatureService from "../../common/service/nomenclature.service";
import Icon from "../Icon";
import React, { useState, useEffect,useCallback} from "react";
import { Switch, Route, useRouteMatch, useHistory, useParams, Redirect } from 'react-router-dom';
import PartItem from "../content/pages/pieces/PartItem";
import Part from "../content/pages/pieces/Part";
import PieceService from "../../common/service/piece.service";
/**
* Node component of a tree
* @param {*} props
* @returns
*/
function TreeNode(props) {
// the child nodes of the current node
const [childs, setChilds] = useState([]);
// Variable that identifies whether a node has been unfolded
const [ nestedActive, setNestedActive] = useState(false);
/**
* Allows to create child elements of the current node
* @param {*} e event
*/
const handleGetDescendants = useCallback((e) => {
//The request is performed only if there are no child elements
if (childs.length < 1) {
let reference = props.item.reference;
let path = props.item.path + ',' + reference;
NomenclatureService.getAllDescendants(path, (e) => {}) .then((response) => {
setChilds(response.data);
setNestedActive(true)
})
.catch((error) => {
console.log(error);
});
}else {
setNestedActive(!nestedActive);
}
});
const levelOneUserRoutes = [
{ name: 'pieces', label: 'Pièces', component: Part, icon: 'IoShapesOutline', path: '/pieces' },
];
let icon;
let iconName;
let item;
if (props.item.type === "ASSEMBLY") {
// Affichage des noeuds de type assemblages
iconName =nestedActive ? "IoCubeOutline" : "IoCube";
icon = <span className="assembly-node tree-icon tree-icon-green">
<Icon iconName={iconName} size={20} />
</span>;
item = <li className="tree-root" onClick={(e) => handleGetDescendants(e)}>
{icon}
{props.item.path !== ",Nomenclature" && props.item.reference}
{props.item.path === ",Nomenclature" && props.item.relatedProject.id}
</li>;
} else {
// Affichage des noeuds de type pièce
iconName ="IoGitBranchOutline"
icon = <span className="piece-node tree-icon tree-icon-primary">
<Icon iconName={iconName} size={20} />
</span>
item = <li className="tree-root" onClick={(e) => handleGetDescendants(e)}>
{icon}
{/* <a className="tree-node" aria-current ="page" href={`${levelOneUserRoutes[0].path}/fab/`+props.item.reference + `/infos`} target = "_blank" > */}
<>
<div className="table-buttons" >
<a className='tree-node' href={`${levelOneUserRoutes[0].path}/fab/`+props.item.reference + `/infos`} target = "_blank">
{props.item.reference} ({props.item.value.name})
</a>
</div>
</>
</li>
}
//Construction des noeuds enfant
let childDivs =childs.map((item) => <TreeNode active={nestedActive} key={item.id} item={item}/>)
return (
<>
{props.active && item}
{
{nestedActive}
&&
<ul className="tree-node">
{childs.length > 0 && childDivs}
</ul>
}
</>
);
}
export default TreeNode;
it would be necessary that when I click on the links of the parts I am redirected towards the road which displays the infos of the part which derives from the page part see image: [1]enter image description here
according to the image, to access the route that contains the information of the part we click on the small icon circled and once it creates a route with path {parts/fab/reference of the part/infos}PartItem.js which derives this current page see image above its path is {part/manufacturing}Part.js here is the code of the page parts/manufacturing where the route of the information of the part is derived
import React, { useState, useEffect, useCallback } from "react"
import { Switch, Route, useRouteMatch, useHistory, Redirect } from 'react-router-dom';
import ManufacturingPart from "./ManufacturingPart";
import TradePart from "./TradePart";
import UnidentifiedPart from "./UnidentifiedPart";
import PieceService from "../../../../common/service/piece.service";
import PartItem from "./PartItem";
import PageInnerMenu from "../../../menu/PageInnerMenu";
import BreadCrumb from "../../../menu/BreadCrumb";
import "../../../../App.css"
/**
* Hook Piece
* @param {*} props
* @returns
*/
function Piece(props) {
// Retrieve the current route information
let match = useRouteMatch();
let history = new useHistory();
// Table of descendant routes of the current route
const subMenuRoutes = [
{ label: "Manufacturing", path: "/manufacturing", component: ManufacturingPart, active: true },
{ label: "Trade", path: "/commerce", component: TradePart, active: false },
{ label: "unknown", path: "/Unidentified", component: UnidentifiedPart, active: false }
]
//States
const [routes, setRoutes] = useState(subMenuRoutes);
const [location, setLocation] = useState(match.path);
//CSS-JS
const pageStyle = {
marginTop: '5vh',
display: 'flex',
paddingLeft: '7.5vw',
flexDirection: "column"
}
/*
** Fonctions
*/
//permet de mettre à jour la valeur du absolutePath (location)
const handlePathChange = useCallback((path) => {
setLocation(path);
}, []);
const handleTabRoutes = useCallback((route) => {
let newRoute = { label: route, path: `/fab/${route}`, active: true }
//Copy du tableau des routes
let tableOfRoutes = [...routes];
//Ajout d'une nouvelle route
tableOfRoutes.push(window.open(newRoute));
setRoutes(tableOfRoutes);
//Redirection vers
history.push( match.url + newRoute.path );
}, []);
return (
<>
<div>
<PageInnerMenu items={routes} />
</div>
<div style={pageStyle}>
<BreadCrumb absolutePath={location} />
{/* Permet de configurer les routes déscendantes de 'pieces' */}
<Switch>
{
routes.map((route, items) => {
if (route.component !== undefined) {
console.log("1--");
console.log(window.location.pathname);
return <Route
exact
path={match.url + route.path}
key={items.id}
children={<route.component onRouteAdd={handleTabRoutes} onPathChange={handlePathChange} />}
/>;
} else {
console.log("2--");
console.log(window.location.pathname);
return <Route
// exact
path={`${match.url}/fab/:id`}
key={items}
children={<PartItem onPathChange={handlePathChange} />}
/>
}
})
}
{/* nous considérons que la route par défaut est le premier élement de subMenuRoutes*/}
<Redirect to={match.url + subMenuRoutes[0].path} />
</Switch>
</div>
</>
);
}
export default Piece;
and here is the page with its code to which I want to access:
/** @jsxImportSource @emotion/react */
import { useEffect, useState } from "react";
import Moment from 'react-moment';
import 'moment/locale/fr';
import { Formik, Form, Field } from 'formik';
import { Switch, Route, Redirect, useHistory, useRouteMatch } from 'react-router-dom';
import PieceService from "../../../../common/service/piece.service";
import Card from "../../../cards/Card";
import TightTabMenu from "../../../menu/tabs/TightTabMenu";
import UserService from "../../../../common/service/user.service";
import STLViewer from 'stl-viewer';
import { css } from '@emotion/react';
import { Step, Stepper } from 'react-form-stepper';
/** Fonctions globales du hook */
export function extractInitialsFromText(text) {
if (texte !== null) {
let initials = null ;
const splited = text.split(" ") ;
if (splited.length > 1) {
initials = splited[0].substring(0, 1) + splited[splited.length - 1].substring(0, 1) ;
return initials.toUpperCase() ;
}
initiales = splited[0].substring(0, 2) ;
return initials.toUpperCase() ;
}
}
/**
* Hook PieceItem, parent des autres Hook interne
* @param {*} props
* @returns
*/
function PieceItem(props) {
//Routes du tab
const tabRoutes = [
{ label : "Informations", path : "/infos", component : Infos, active : true },
{ label : "Détails", path : "/details", component : Détails, active : false },
]
const [piece, setPiece] = useState({}) ;
let match = useRouteMatch() ;
const { id } = match.params
/**
* Récupère les infos d'une pièce
*/
function getPiece(id) {
PieceService.getOneManPiece(id).then((response) => {
setPiece(response.data)
})
.catch((error) => {
console.log(error);
});
}
useEffect(() => {
// Notification du chemin au parent
props.onPathChange(match.url);
getPiece(id);
}, [id]);
const cardStyle = {
backgroundColor: "white",
display: "flex",
flexDirection: "column",
width: "85vw"
}
const tabBodyStyle = css`
padding: 1rem;`
const cardBody =
<div>
<TightTabMenu items={tabRoutes} />
<div css={tabBodyStyle}>
<Switch>
{
tabRoutes.map((route, index) => {
return <Route
exact
path={match.url + route.path}
key={index}
children={<route.component data={piece} />}
/>;
})
}
{/* nous considérons que la route par défaut est le premier élement de subMenuRoutes*/}
<Redirect to={match.url + tabRoutes[0].path} />
</Switch>
</div>
</div>
return (
<div>
<Card cardStyle={cardStyle} body={cardBody} />
</div>
)
}
But I can't do it, I can get the path from the part/fab/part reference/info route, but I always end up being redirected to the part/manufacturing path.
please can someone help me?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
