Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 884
Mark_Bruckert Avatar asked Jan 26 '26 17:01

Mark_Bruckert


2 Answers

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'));
like image 59
webprojohn Avatar answered Jan 29 '26 06:01

webprojohn


Use react-router to define your pages and switch between them

https://reacttraining.com/react-router/

like image 41
Vinod CG Avatar answered Jan 29 '26 05:01

Vinod CG