how to remove routing in a separate component - javascript

how it is possible to remove this routing in a separate component? I tried to do it through the map but it did not work
I want only one route to remain and when you click on a certain link, 'path' changes in it
const Home = ({ code }) => {
return (
<div className="wrapper__flex_main">
<TheNav {...code} />
<Routes>
<Route path='/' element={<Main code={code} />} />
<Route path='/search' element={<TheSearchTrack code={code} />} />
<Route path='/likes' element={<Likes code={code} />} />
<Route path='/artist' element={<Artist code={code} />} />
<Route path="/genre/:id" element={<GenreTemplate code={code} />} />
<Route path="/artist/:id" element={<ArtistPages code={code} />} />
<Route path="/genretrack/:id" element={<GenreTrack code={code} />} />
<Route path="/track/:id" element={<Track code={code} />} />
</Routes>
</div>
)
}
export default Home

const navigate = useNavigate();
...
const loginHandler = () => {
... business logic ...
// if logic true
navigate('navigate-path', { replace: true }); // redirect!!!
};
You can use something like this , this prevent user navigation to other pages

Related

How to use 'CSSTransition' in react-router that has 'Link' in each component?

I have a 'CSSTransition' component encompassing the 'Routes', but I can't put a function that changes the 'state' in the 'Link' components, because each one is in different files
In routes.js
const Routes = () =\> {
const [isEnter, setIsEnter] = useState(false)
return(
<CSSTransition
in={isEnter}
timeout={4000}
classNames='fade'
>
<Router>
<Routes>
<Route exact path='/' element={<StartPage />} />
<Route path='/question-one' element={<FirstQuestion />} />
<Route path='/question-two' element={<FavoritePerson />} />
<Route path='/question-three' element={<ChoseMode />} />
<Route path='/first-message' element={<SuccessPage />} />
<Route path='/question-four' element={<FavoriteDate />} />
<Route path='/last-question' element={<DoYouWannaDateMe />} />
</Routes>
</Router>
</CSSTransition>
)
}
export default Routes;
In each component
export default function StartPage() {
return (
\<div className="card"\>
<h1 className='card-title'>Está pronta?</h1>
<form>
<Link to='/question-one' className='button-submit'
onClick={()=>{
setIsEnter()
}}
>SIM</Link>
<input type='button' value='NÂO' onClick={warningMessage}></input>
</form>
</div>
);
}
The function 'setIsEnter()', that change the state of 'CSStransition' is not defined in StartPage.js
If I understand you correctly, i have this option.
Declare component, that you need, and pass it for all routes as a props.
function func() {...}
<Route path='/question-one' element={<FirstQuestion func={func} />}

How to create a 404 page with dynamic routes in React? [duplicate]

function App() {
return (
<RecoilRoot>
<Router>
<Navbar />
<Routes>
<Route path={"/"} element={<Home />} />
<Route path={`/page/:menu`} element={<MovieMenu />} />
<Route path={`/movie/:id`} element={<Detail />} />
<Route path={`/search/:searchText`} element={<Search />} />
<Route path={"*"} element={<NotFound />} />
</Routes>
</Router>
</RecoilRoot>
);
}
If i process 404 page in the above way, / handle it well, but <NotFound /> not be rendered if any path is entered after /page/fldlfsd;lf; or /search/dsklfskldf. Is there a way?
Paths like "/page/fldlfsd;lf;" and "/search/dsklfskldf" will be matched and rendered by the Routes component. The route param validation needs to occur in the routed component.
Each component can use the useParams hook to access the route param, validate it, and redirect to the NotFound route if param is invalid.
To help with this I suggest creating a discrete route to render NotFound so you can imperatively redirect to it from components and create a redirect route to handle unknown routes.
Example:
function App() {
return (
<RecoilRoot>
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/page/:menu" element={<MovieMenu />} />
<Route path="/movie/:id" element={<Detail />} />
<Route path="/search/:searchText" element={<Search />} />
<Route path="/404" element={<NotFound />} />
<Route path="*" element={<Navigate to="/404" replace />} />
</Routes>
</Router>
</RecoilRoot>
);
}
...
MovieMenu
const navigate = useNavigate();
const { menu } = useParams();
useEffect(() => {
... logic to validate menu param ...
if (invalidMenu) {
navigate("/404", { replace: true });
}
}, [menu, navigate]);
...

I'm making a online tutorial website from react.js which has course and course has some sub topic .IS there any short cut for this code which I rote

In my code, there are many imports (38 import components) and routes(38 routes) so can simplify those into a few imports and routes is there any way available...???
function App() { return (
<Router>
<SideBar>
<Routes>
<Route path="/Architecture" element={<ReactJs_Architecture />} />
<Route path="/JSX" element={<ReactJs_JSX />} />
<Route path="/Components" element={<ReactJs_Components />} />
<Route path="/Styling" element={<ReactJs_Styling />} />
<Route path="/Properties" element={<ReactJs_Properties />} />
<Route path="/EventManagement" element={<ReactJs_EventManagement />} />
<Route path="/StateManagement" element={<ReactJs_StateManagement />} />
<Route path="/Redux" element={<ReactJs_Redux />} />
<Route path="/Animation" element={<ReactJs_Animation />} />
<Route path="/Home" element={<NodeJs_Home />} />
<Route path="/Node_Introduction" element={<Node_Introduction/>} />
<Route path="/EnvironmentSetup" element={<NodeJs_EnvironmentSetup />} />
<Route path="/REPLTerminal" element={<NodeJs_REPLTerminal />} />
<Route path="/PackageManager" element={<NodeJs_PackageManager />} />
<Route path="/Buffers" element={<NodeJs_Buffers />} />
<Route path="/Streams" element={<NodeJs_Streams />} />
<Route path="/WebModule" element={<NodeJs_WebModule />} />
<Route path="/ScalingApplications" element={<NodeJs_ScalingApplications />} />
<Route path="/Packaging" element={<NodeJs_Packaging />} />
<Route path="*" element= { < not found />} />
</Routes>
</SideBar>
</Router>
);
}
export default App;
If your items are long always try to create an array and list all your routes there like this
const ROUTE_PATHS = {
PRICING: "/pricing",
ACTIONS: "/actions",
};
const routeItems = [
{
name: "Pricing",
path: ROUTE_PATHS.PRICING,
Component: Pricing,
},
{
name: "Bulk Actions",
path: ROUTE_PATHS.ACTIONS,
Component: Actions,
},
];
And now add a loop to iterate over all the routes
<Routes>
{routeItems.map(item => {
const { Component } = item;
return (
<Route
key={item.name}
path={item.path}
element={
<Component />
}
/>
);
})}
</Routes>
Now it made simple.

react-router-dom useNavigate

I have a component, where i have to call navigate to main page, but navigate is not working, where is my fall? I know that userName is changing but redirect doesn't happening
Index.js
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
App.js
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/settings" element={<Settings />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
)
Login.js
const dispatch = useDispatch();
const user = useSelector((store) => store.user);
let navigate = useNavigate();
const onSubmitForm = (e) => {
e.preventDefault();
dispatch({
type: FETCH_USER,
payload: { login: user.login, password: user.password },
});
}
useEffect(() => {
if(user.userName) {
navigate("/login");
}
}, [user.userName])
I am not sure if it is the case but try changing the order of your paths to this:
return (
<Switch>
<Route path="/login" element={<Login />} />
<Route path="/settings" element={<Settings />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/" element={<Home />} />
</Switch>
)
I had a similar thing before and somehow navigation was always navigating to the Home because path"/" was on top.
Also a small thing, I normally use the Routes with Switch. In my experience above structure should work

Redirect to specific page if localstorage value not found in react

I am using reactjs.
I have multiple following routes in my index.js file
<BrowserRouter>
<App>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/Login" component={SignIn} />
<Route exact path="/Sign-up" component={SignUp} />
<Route exact path="/Orders" component={Orders} />
<Route exact path="/Category" component={Category} />
<Route exact path="/Shops" component={Shops} />
</Switch>
</App>
</BrowserRouter>
initially when user goes to base URL suppose
Http://localhost:3000
he should be redirected to
Http://localhost:3000/Shops page if value of localstorage item is null
and also if user tries to visit other pages he should be redirected to the /Shops page.
One way of doing this is using HOC but further i'll be adding auth soo there i'll have to wrap the component in route with HOC like this
<Route exact path="/Orders" component={AuthGuard(Orders)} />
I dont know whether I can do like this
<Route exact path="/Orders" component={AuthGuard, ShopGuard(Orders)} />
soo how can i achieve this without using HOC or how can I wrap 2 HOC for a single component.
Thanks.
function HandleRedirection() {
const RedirectToShop = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={(props) =>
localStorage.getItem('user') ? (
<App>
<Component {...props} />
</App>
) : (
<Redirect to="/shop" />
)}
/>
);
};
return (
<BrowserRouter basename={`/`}>
<Switch>
<Route path={`/shop`} component={Shops} />
<RedirectToShop exact path={`/login`} component={Signin} />
<RedirectToShop exact path={`/order`} component={Order} />
<RedirectToShop exact path={`/category`} component={Category} />
<Redirect to="/shop" />
</Switch>
</BrowserRouter>
);
}
Create a custom Route component that can check localStorage and redirect to "/shop" if condition is (or isn't?) met.
const ShopGuardRoute = ({ component: Component, ...props }) => (
<Route
{...props}
render={routeProps => {
const item = localStorage.getItem("key");
// Do all your conditional tests here
return item !== null ? (
<Component {...routeProps} />
) : (
<Redirect to="/shop" />
);
}}
/>
);
Usage
<BrowserRouter>
<App>
<Switch>
<ShopGuardRoute path="/Login" component={SignIn} />
<ShopGuardRoute path="/Sign-up" component={SignUp} />
<ShopGuardRoute path="/Orders" component={Orders} />
<ShopGuardRoute path="/Category" component={Category} />
<Route path="/Shops" component={Shops} />
<Route path="/" component={Home} />
</Switch>
</App>
</BrowserRouter>
If you plan on adding an authentication check then auth-workflow may help.
I think you can just do something like this on all the required pages if(condition // your local storage null check) { history.push(/yourPath, dataIfAny); }

Categories