React Route without link

Asked

Viewed 526 times

0

I am starting my studies with React and I am using React Router to navigate between pages by clicking on links in the menu, but I have a question, how do I access a page without a link ? How do I set a route in this case ?! The project I created using the create-React-app and the route I want to set up is /login to load the class Login.js.

Main.js code with menu:

import React, { Component } from "react";
import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";
import Home from "./Home";
import Stuff from "./Stuff";
import Contact from "./Contact";


class Main extends Component {
  render() {
    return (
    <HashRouter>
        <div>
        <h1>Simple SPA</h1>
        <ul className="header">
            <li><NavLink exact to="/">Home</NavLink></li>
            <li><NavLink to="/stuff">Stuff</NavLink></li>
            <li><NavLink to="/contact">Contact</NavLink></li>
        </ul>


        <div className="content">
            <Route exact path="/" component={Home}/>
            <Route path="/stuff" component={Stuff}/>
            <Route path="/contact" component={Contact}/>
        </div>
        </div>
    </HashRouter>
    );
  }
}

export default Main;

Login.js code that I want to configure the route and access directly through the URL:

import React, { Component } from "react";

class Login extends Component {
    render() {

    return (
        <div>
            <form>
                <label>
                    Name:
                <input type="text" name="name" />
                </label>
                <input type="submit" value="Submit" />
            </form>
        </div>
    );
    }
}

export default Login;

1 answer

5


First you must import the login on Main.js
Main.js

import Login from "./Login";

Then still inside your Main.js you must add the route

<div className="content">
    // Rota login adicionada
    <Route exact path="/login" component={Login}/>

    <Route exact path="/" component={Home}/>
    <Route path="/stuff" component={Stuff}/>
    <Route path="/contact" component={Contact}/>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.