Search code examples
reactjsreact-navigationreact-bootstrap

call component on nav.link href in react js


i am new to reactjs, please help me to assign coponent AddApiComp to href of navlink to open on page load

import { Navbar,  Nav } from 'react-bootstrap';

import AddApiComp from "./";

function Navigfgation(){

return(

\<Navbar collapse \>

\<Navbar.Brand href="#"\>Developer API\</Navbar.Brand\>
    

 \<Navbar.Toggle aria-controls="responsive-navbar-nav"/\>

\<Navbar.Collapse id="responsive-navbar-nav"\>
\<Nav className="mr-auto"\>

\<Nav.Item\>

\<Nav.Link href="./Add-Api-Controller" title="Add Api"\>{AddApiComp}\</Nav.Link\>

\</Nav\>
\</Navbar.Collapse\>


\</Navbar\>
)
}

export default Navigation;

on click of ** Add API**, *AddApiComp *component should display


Solution

  • React is not opinionated and does not include a routing solution. That's why you are free to use any of them. The most popular solution is "React Router". I have implemented a working example using your code and react router 6: https://codesandbox.io/s/react-router-6-example-ll16cx

    Please follow this tutorial to understand the implementation: https://reactrouter.com/docs/en/v6/getting-started/tutorial

    One tricky part is that you want to use frontend routing (without page reload, SPA) and at the same time having your bootstrap stylings on links. You can achieve this by using Nav.Link and using its as property:

    import { Nav } from "react-bootstrap";
    import { Link } from "react-router-dom";
    <Nav.Link as={Link} to="/add-api-controller">