javascriptreactjsreact-router

Switch Between Pages in React


I am a total React newbie and have a (probably) stupid question. How do I switch between DIFFERENT javascript pages in React.js?

I have a button on one of my pages, that I want to link to another javascript page. I know about the router, but that does not fit my needs.

Web App Structure

Thank You, Mark Bruckert


Solution

  • This is based on the example from the react-router docs. React Router is probably the easiest client side routing solution. Happy coding.

    See the complete example on Stackblitz.

    import React, { Component } from 'react';
    import { render } from 'react-dom';
    import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
    
    const Nav = () => (
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
        </ul>
      </div>
    );
    
    const HomePage = () => <h1>Home Page</h1>;
    const AboutPage = () => <h1>About Page</h1>;
    
    class App extends Component {
      constructor() {
        super();
        this.state = {
          name: 'React'
        };
      }
    
      render() {
        return (
          <Router>
    
            {/* Router component can have only 1 child. We'll use a simple
              div element for this example. */}
            <div>
              <Nav />
              <Route exact path="/" component={HomePage} />
              <Route path="/about" component={AboutPage} />
            </div>
          </Router>
        );
      }
    }
    
    render(<App />, document.getElementById('root'));