2

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

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Subin Thankachan
  • 101
  • 1
  • 1
  • 7

5 Answers5

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>
);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Why do we export Route component App here? – Subin Thankachan Oct 23 '18 at 08:50
  • 1
    The component that uses Routes must be wrapped in Router and hence exporting a functional component here – Shubham Khatri Oct 23 '18 at 08:58
  • 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? – Subin Thankachan Oct 23 '18 at 09:11
  • 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 – Shubham Khatri Oct 23 '18 at 09:18
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>
Victor Jozwicki
  • 700
  • 2
  • 10
  • 24
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);
Sunil Kumar
  • 420
  • 4
  • 13
1

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;
Musty
  • 41
  • 4
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>
            </>
    );
};

DarkTrick
  • 2,447
  • 1
  • 21
  • 39