'Routing Inside Routed Components in React

I have an top level App componenet which contains and SideBar and MainBody. Here's my App Component,

function App() {
    return (
        <div className="pageContainer">
            <Router>
                <Sidebar/>
                <MainBody/>
            </Router>
        </div>
    );
}

The SideBar contains the links which are rendered in the MainBody:

const Sidebar = () => {
    
    return (
        <div className="sideBarWrapper">
            <figure className="logoContainer"></figure>

            <nav className="sideBarNavContainer">
                <ul>
                    <li><NavLink exact to="/">A</NavLink></li>
                    <li><NavLink exact to="/">B</NavLink></li>
                    <li><NavLink exact to="/">C</NavLink></li>
                    <li><NavLink exact to="/">D</NavLink></li>      
                </ul>
            </nav>
        </div>

    )
}

Here's the MainBody

const MainBody = () => (
    <main className="mainBodyWrapper">
        <header className="headerContainer">
            
        </header>
        <main>
            <Routes>
                <Route path="/" exact element={<A/>}/>
                <Route path="/b" element={<B/>}/>
                <Route path="/c" element={<C/>}/>
                <Route path="/d" element={<D/>}/>
                <Route element={<PageNotFound/>}/>
            </Routes>
        </main>
        <footer className="footerContainer">
            

        </footer>
    </main>
)

Upto this point everything is fine. Now Inside Component A/B/C/D I've a Read more button. On Clicking the button I want to render a component X. Similarly X has a Back button, which should render A back. How can I achieve this. Here's Component A and X

const A = () => {
  
    return(
        <Link to="/platform/details">
             <button>Read more</button>
        </Link>      
    )
}

const X = () => {
  
    return(
        <Link to="/platform/details">
             <button>Back</button>
        </Link>      
    )
}


Solution 1:[1]

Instead of a link, you can use history:

const X = () => {
const history = useHistory();

return(
    <button onClick={history.goBack}>Back</button>
)

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Androidz