3

I am new to React and I want to navigate to another component on button click. I just want to perform a simple routing. This is the code that I tried. But I am not able to route it.

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'
import Hello from './HelloComponent';
class App extends Component {

  constructor(props) {
    super(props);
    this.try = this.try.bind(this)
  }
  try = () => {
    alert();
    <div>
      <Router>
        <Route path="/hello" component={Hello} />
      </Router>
    </div>
  }
  render() {
    return (
      <div className="App">
        <div className="container">

          <button id="b1" onClick={this.try}>Click me</button>
        </div>
      </div>
    );
  }
}
export default App;

Please help me with this code to perform basic routing in react JS

3
  • Check this for Basic routing example Commented Oct 23, 2018 at 6:48
  • @NarendraJadhav This is for links ,not on button click Commented Oct 23, 2018 at 6:50
  • I know but this will help you to achive your requirement Commented Oct 23, 2018 at 6:51

5 Answers 5

6

You cannot return JSX to onClick handler since it won't do anything with it.

You need to configure your Routes in render in advance and use history.push to change the Route

Below is a sample code that you can refer

import React, { Component } from 'react';
import { BrowserRouter as Router, Route,Switch, Redirect} from 'react-router-dom'
import Hello from './HelloComponent';
class App extends Component {
  try = () => {
      this.props.history.push('/hello');
  }
  render() {
    return (
      <div className="App">
        <div className="container">
            <button id="b1" onClick ={this.try}>Click me</button>
            <Route path="/hello" component={Hello}/>
        </div>
      </div>
    );
  }
}
export default () => (
   <div>
      <Router>
           <Route component={App} />
      </Router>
  </div>
);
Sign up to request clarification or add additional context in comments.

4 Comments

Why do we export Route component App here?
The component that uses Routes must be wrapped in Router and hence exporting a functional component here
Is there any way to export Router? Suppose if I already have an export in my code like, export default compose( connect(mapStateToProps, {signOut}), translate('SampleApp') )(SampleApp); Where will I add this Router component?
Ideally you will have only one Router component in your code and it will be at the top most level. I recommend that you read the react-router documentation once. They provide a good deal of information
3

I recommend you look at the doc.

<Route path="/hello" component={Hello}/> will display the component Hello exactly where the <Route/> is, but I think your function will do nothing here as it returns a <div> but where does it go?

You need some sort of "higher" component that will render your routes, then call a <Link/>

Then try nesting the button inside the <Link/> ?

<Link to="/??">
     <button id="b1">
          Click me
     </button>
</Link>

Comments

2

I have created a demo that brings it all together. It has three files App.js, About.js, Contacts.js. To Navigate to any component, you need to add its route in App.js, Then depending on the location of your button (About.js), wrap it with Link that helps the element navigate to the specified route. When clicked, the Contacts component should be loaded. Hope this helps. code demo

App.js

import React from "react";
import { Switch, Route, BrowserRouter } from "react-router-dom";
import About from "./About";
import Contact from "./Contacts";

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/" component={About} exact />
        <Route path="/contacts" component={Contact} />
      </Switch>
    </BrowserRouter>
  );
}

export default App;

About.js

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

function About() {
  return (
    <div>
      <p>
        Lorem Ipsum is simply dummy text of the printing and typesetting
        industry.
      </p>
      <Link to="/contacts">
        <button>click me</button>
      </Link>
    </div>
  );
}
export default About;

Contacts.js

import React from "react";

function Contact() {
  return <div>Call me!!</div>;
}
export default Contact;

Comments

1

in your code

try = () => {
             alert();
            <div>
              <Router>
                   <Route path="/hello" component={Hello}/>
              </Router>
            </div>
           }

your just pushing the route and it's not a action to take you to different page

bellow code will work fine and it's good practice to place router in separate component. click here you can find this code in codesandbox

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import "./styles.css";

function RouterComponet() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/user" component={User} />
      </Switch>
    </Router>
  );
}
class App extends Component {
  constructor(props) {
    super(props);
  }
  onClick = () => {
    this.props.history.push("/user");
  };
  render() {
    return (
      <div>
        <h1>App component</h1>
        <a onClick={this.onClick} className="link">
          click here
        </a>{" "}
        to user page
      </div>
    );
  }
}

class User extends Component {
  constructor(props) {
    super(props);
  }
  onClick = () => {
    this.props.history.push("/");
  };
  render() {
    return (
      <div>
        <h1>User Componet</h1>
        <a onClick={this.onClick} className="link">
          click here
        </a>{" "}
        to back
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<RouterComponet />, rootElement);

1 Comment

this doesn't seem to be what the OP was asking for.
0

This is the first SO post on google, so I'd like answer the question with updated coding style and answer:

From react v6 you use the useNavigation hook. (Reference)

import { useNavigate } from 'react-router-dom';


export const MyComponent = () => {
    const navigate = useNavigate();
    return (
            <>
                    <button
                            onClick={() => {
                                    navigate('/');
                            }}
                    >
                            click me
                    </button>
            </>
    );
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.