I decided to improve the routing in the pet project and found such an opportunity in the guide so that it would be possible to add chats.
import React from 'react';
import { Routes, Route } from 'react-router-dom'
import Layout from './Layout';
import Profile from "./Profile";
import PropTypes from "prop-types";
export default class Router extends React.Component {
static propTypes = {
chatId: PropTypes.number,
};
static defaultProps = {
chatId: 1
};
render() {
return (
<Routes>
<Route path='/' element={<Layout />} />
<Route
path='/chat/:chatId/'
render={obj => <Layout chatId={Number(obj.match.params.chatId)} />}
/>
{/*<Route path='/chat/1' element={<Layout chatId={1/>} />*/}
{/*<Route path='/chat/2' element={<Layout chatId={2/>} />*/}
{/*<Route path='/chat/3' element={<Layout chatId={3/>} />*/}
<Route path='/profile' element={<Profile />}/>
</Routes>
)
}
}
I used the commented text before, but adding chats is unrealistic to implement with it. ChatId, I pass it everywhere as props.
2
Answers
One simple way to do this is create an array of
chatIds
andmap
over it and the use it as:CODESANDBOX
Convert
Layout
to a React function component so it can read a declaredchatId
route path parameter.Example:
Update the router/routes to render a single dynamic route for the
Layout
and use the root"/"
route to redirect to the default"/chat/1"
route.Example:
Router.js
index.js
Demo