PyDive PyDive - 9 months ago 37
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


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
links, but it is to show that I want those to render other parts of the site as a response to clicking on a

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

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

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

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

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

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
and gave me an example on how to achieve my goal without it. Cheers.

Answer Source

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.