pratteek shaurya
pratteek shaurya

Reputation: 960

Open new page on click of button in react

I want to open FormStatus in a new page when I click a button in Form page. Below is my code.

App.js:

import Form from "./components/Form";
import FormStatus from "./components/FormStatus";
import { BrowserRouter as Router, Route } from "react-router-dom";

function App() {
  return (
    <Router>
      <div className="App">
        <Route path="/" component={Form}/>
        <Route exact path="/form-status" component={FormStatus}/>
      </div>
    </Router>
  );
}

export default App;

Form.js

import { Link } from "react-router-dom";

const Form = () => {
    return (
        <div>
            <h1>Form Page</h1>
            <Link to="/form-status"><button>click</button></Link>
        </div>
    );
}
export default Form;

FormStatus.js:

import React, {Component} from "react";

class FormStatus extends Component {
    render(){
        return(
            <h1>Form Status Page</h1>
        )
    }
}
export default FormStatus;

when I click on the button on Form component, my url changes to http://localhost:3000/form-status, but instead of opening a new page, my FormStatus component comes below Form component.

I want FormStatus to open new a page and only shows contents of my FormStatus component and not contents of Form component

Upvotes: 2

Views: 2791

Answers (1)

SMAKSS
SMAKSS

Reputation: 10520

Well, to make this work, you need to change two things in your current code.

  1. Use the Switch from the react-router-dom and wrap your routes within it.
  2. Make your home page (/) route exact instead of the /form-status route, because the /form-status route also includes the leading slash (/). So since both of them will match the expected route it will render them together.

So your code should be something like this in the App.js:

import React from "react";
import Form from "./components/Form";
import FormStatus from "./components/FormStatus";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

export default function App() {
  return (
    <Router>
      <Switch>
        <div className="App">
          <Route exact path="/" component={Form} />
          <Route path="/form-status" component={FormStatus} />
        </div>
      </Switch>
    </Router>
  );
}

Working Demo:

CodeSandbox

Upvotes: 2

Related Questions