Rare
Rare
RReactiflux
Created by Rare on 7/28/2024 in #react-forum
React router best practice
Im new to react router, I want to pass state down to my components that are in different URL paths This is the file I'm stuck with, App.tsx
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Greeting from './pages/Greeting';
import NotFound from './pages/NotFound';
import ChangeName from './pages/ChangeName';
import { useState } from 'react';

export default function App() {
const [username, setUsername] = useState('John');
const router = createBrowserRouter([
{
index: true, // path: '/'
element: <Greeting username={username} />,
errorElement: <NotFound />,
},
{
path: '/greeting',
element: <Greeting username={username} />,
},
{
path: '/change-name',
element: <ChangeName username={username} setUsername={setUsername} />,
},
]);
return <RouterProvider router={router} />;
}
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Greeting from './pages/Greeting';
import NotFound from './pages/NotFound';
import ChangeName from './pages/ChangeName';
import { useState } from 'react';

export default function App() {
const [username, setUsername] = useState('John');
const router = createBrowserRouter([
{
index: true, // path: '/'
element: <Greeting username={username} />,
errorElement: <NotFound />,
},
{
path: '/greeting',
element: <Greeting username={username} />,
},
{
path: '/change-name',
element: <ChangeName username={username} setUsername={setUsername} />,
},
]);
return <RouterProvider router={router} />;
}
Here, I have created the router from createBrowserRouter inside my App react component, is this allowed, is it fine? I'm asking because in the react router docs tutorial, they created the router outside the component. But this way, I cannot access state variable and pass them as props. So once again, is it okay to create a router from createBrowserRouter inside my component?
4 replies