PyDive PyDive - 1 month ago 6
Javascript Question

Rendering other components through an <a> link

In the example below, I have two functional components that give the idea of being separate pages, though, of course, they only display different colored

<div>
boxes.

const Home = () =>
<div style={{background:'red', height: 100, width: 100}}></div>;

const About = () =>
<div style={{background:'blue', height: 100, width: 100}}></div>;


Now, if I wanted to create a navigation bar that links to certain parts of my site -- ignoring the possible wrong use of the
<a>
links, but it is to show that I want those to render other parts of the site as a response to clicking on a
Navbar
option.

const Navbar = () =>
<div>
<a href='#'>Home</a>
<a href='#'>About</a>
</div>;


If I have a component named
App
that renders different pages for me:

const App = () =>
<div>
<Navbar />
// Render current page here; default is the `Home` component.
</div>;

ReactDOM.render(<App />, document.getElementById('app'));


How could I actively update my
App
component to render different pages based off the clicking of links, or elements, in my
Navbar
?

EDIT:
Soviut and finalfreq, thank you for your answers! I came from Codecademy's ReactJS course, so the transition into the 'real world' of Javascript and React has been somewhat difficult, since I've had to learn about ES6, and being ignorant of most JS libraries. Anyway, I appreciate that you guys pointed me in the direction of
react-router
and gave me an example on how to achieve my goal without it. Cheers.

Answer

This is what react-router was built to do.

While doing it manually isn't recommended, it would work by emitting click events that call a callback function passed into it from a parent component that contains your "pages". That callback would tell the parent container which navigation link was clicked and it would decide which page to show and which to stop rendering.