Routing in React JS on click - reactjs

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

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>
);

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>

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);

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;

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>
</>
);
};

Related

Create a Default page without sidebar and route

Goal:
Show the first page (default page) that contain a button that goes to the page with sidebar link Home and About using Router.
Problem:
Today, you have a menu with link Home and About but if I want a default page (that is the main page that you enter) and then you go to another page that has sidebar and using route.
How should it be created?
Info:
*Newbie in Reactjs
*The main page (default) should not contain any sidebar or any route.
Stackblitz:
https://stackblitz.com/edit/react-k19hye?
import React from 'react';
import './style.css';
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>;
export default 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'));
In order to set another default page, you should first update the route to HomePage to /home. And then define another route for the DefaultPage like <Route exact path="/" component={DefaultPage} />. In order to hide sidebar on the DefaultPage, you can use Switch to show only DefaultPage on route /.
You can take a look at this updated stackblitz forked from your original example for a live working example. Here is the final full code of this usage:
import React from 'react';
import './style.css';
import React, { Component } from 'react';
import { render } from 'react-dom';
import {
BrowserRouter as Router,
Route,
Link,
Switch,
useHistory,
} from 'react-router-dom';
const Nav = () => (
<div>
<ul>
<li>
<Link to="/home">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</div>
);
const DefaultPage = () => {
const history = useHistory();
return (
<div>
<h1>Default Page</h1>
<button onClick={() => history.push('/main')}>go to main</button>
</div>
);
};
const HomePage = () => <h1>Home Page</h1>;
const AboutPage = () => <h1>About Page</h1>;
export default class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
};
}
render() {
return (
<Router>
<Switch>
{/* Router component can have only 1 child. We'll use a simple
div element for this example. */}
<Route exact path="/" component={DefaultPage} />
<div>
<Nav />
<Route exact path="/home" component={HomePage} />
<Route exact path="/about" component={AboutPage} />
</div>
</Switch>
</Router>
);
}
}
render(<App />, document.getElementById('root'));

How to redirect to completely new page after user click in react?

I have a parent component which is rendering some stuff and a child component which is getting some props from parent component. And when user click button in Parent then it should redirect to completely new Page of child componen.
Parent Component
import React from "react";`enter code here`
import "./styles.css";
import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom'
import ChildComponent from './ChildComponent'
export default function App() {
const someData = {
name : "Joh Doe"
}
return (
<div className="App">
<h1>This is parent Component</h1>
<Router>
<Link to='/secondpage'>Click me for Second Page</Link>
<Route
path='/secondpage'
render={(props) => (
<ChildComponent {...someData} isAuthed={true} />
)}
/>
</Router>
</div>
);
}
ChildComponent.js
import React from "react";
export default function ChildComponent(props) {
console.log("Data", props);
return <div>This is Second Page. It should open in new page. Also it should render incoming props</div>;
}
Work Demo
try doing this:
import React from 'react';
import {BrowserRouter as Router,Route, Redirect,Switch} from 'react-router-dom';
import Home from './App.js';
import Tutorials from './tutorials.js';
function Routes() {
return (
<Router>
<div>
<Switch>
<Route path="/" component = {Home}>
<Redirect from = "/blog/" to="/tutorials/" />
<Route path = "/tutorials/" component = {About} />
</Switch>
</div>
</Router>
)
}
i am change code .
parent component
import React from "react";
import { Link } from "react-router-dom";
export default function ParentComponent(props) {
console.log("Data", props);
return (
<div className="App">
<h1>This is parent Component</h1>
<Link to="/secondpage">Click me for Second Page</Link>
</div>
);
}
child component
import React from "react";
export default function ChildComponent(props) {
console.log("Data", props);
return (
<div>
This is Second Page. It should open in new page. Also it should render
incoming props
</div>
);
}
app component
import React from "react";
import "./styles.css";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import ChildComponent from "./ChildComponent";
import ParentComponent from "./parentComponent";
export default function App() {
const someData = {
name: "Joh Doe"
};
return (
<div className="App">
<Router>
<Switch>
<Route exact path="/secondpage">
<ChildComponent {...someData} isAuthed={true} />
</Route>
<Route exact path="/" component={ParentComponent} />
</Switch>
</Router>
</div>
);
}
Work Demo

Open modal in React Router

In my react project, this is my App.js:
import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Modal from "./Modal";
export default function BasicExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
</ul>
<hr />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/modal">
<Modal />
</Route>
</Switch>
</div>
</Router>
);
}
function Home() {
return (
<div>
<h2>Home</h2>
<p>
Please <Link to="/modal/1">Click Here</Link> for see details.
</p>
</div>
);
}
When you click on "Click Here", the modal was open, but my home page will be disappear. how can open this modal without destroying the home page ?
DEMO HERE:
https://codesandbox.io/s/react-router-basic-2g9t1
Modals should not be in a route as they are supposed to be on top of another page, not a page themshelves. If you want my opinion I would suggest you to put the modal in any of the pages and control if it is opened or not with a react state:
import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Modal from "./Modal";
export default function BasicExample() {
return (
<Router>
<div>
<Switch>
<Route exact path="/" component={Home} />
</Switch>
</div>
</Router>
);
}
const Home = () => {
const [ isModalOpened, setModalOpened ] = useState(false);
return (
<div>
<h2>Home</h2>
<button onClick={() => setModalOpened(!isModalOpened)}
<Modal isOpened={isModalOpened}>
...modal content here
</Modal>
</div>
);
}
And your modal component should look like something like this:
const Modal = ({ isOpened, children }) => (
<div>
{
isOpened &&
{ children }
}
</div>
)
If this helps you make sure to mark it as a good response!

How to go to another domain/route when even happening in React (Router)

What if the Home component includes a button, and I want that when it click on, it will go to another Route (domain). For example - choose component?
How can I do that ?
The main component:
function App() {
return (
<Router> {/*Everything inside this will be capble to routing*/}
<div className="App">
<h1>CarLeas</h1>
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/choose" component={Choose}/>
<Route path="/whochoose" component={Whochoose}/>
<Route path="/reback" component={Reback}/>
</Switch>
</div>
</Router>
);
}
Home component:
import React from "react";
class Home extends React.Component {
render() {
return (
<div>
<img src="https://www.trustford.co.uk/img/campaigns/all-new-ford-focus/2018-08-22/all-new-focus-banner-2000x500.jpg"></img>
<p>Rent a Car</p>
<button>Start Now</button> {/*Button - If event onclick happend show the "choose" component*/}
</div>
)
}
}
export default Home;
You can use this.props.history.push() to switch routes programmatically, in your case:
this.props.history.push("/choose");
However, I would recommend you using <Link> from react-router for linking, if there is no other logic, like so:
import React from "react";
import {Link} from "react-router";
class Home extends React.Component {
render() {
return (
<div>
<img src="https://www.trustford.co.uk/img/campaigns/all-new-ford-focus/2018-08-22/all-new-focus-banner-2000x500.jpg"></img>
<p>Rent a Car</p>
<Link to="/choose">Start Now</Link>
</div>
)
}
}
export default Home;
import React from "react";
class Home extends React.Component {
render() {
const { history } = this.props;
return (
<div>
<img src="https://www.trustford.co.uk/img/campaigns/all-new-ford-focus/2018-08-22/all-new-focus-banner-2000x500.jpg"></img>
<p>Rent a Car</p>
<button onClick={()=> history.push('/choose') }>Start Now</button>}
</div>
)
}
}
export default Home;

How to hide and show a router component on an onclick event in react js

I am trying to hide and show a router component on an onclick event in REACTJS.but didn't find the way i could do that.Help me with that.
here's my code-
import React from 'react';
import { BrowserRouter as Router,Route, Link, Switch} from 'react-router-dom';
import SignIn from './SignIn'
export default class Clicksigningin extends React.Component{
render(){
return(
<div>
<Router>
<div>
<Link to={'/SignIn'}><button className='btn btn-danger'>Sign In</button></Link>
<Switch>
<Route exact path = '/SignIn' component = {SignIn} />
</Switch>
</div>
</Router>
</div>
)
}
}
Better way to do this is get rid of router for this particular component.
Inside a single component (say SignIn) you can have a button which will toggle (show/hide) the signIn part.
import React from 'react';
import { BrowserRouter as Router,Route, Link, Switch} from 'react-router-dom';
import SignIn from './SignIn'
export default class Clicksigningin extends React.Component{
constructor(props){
super(props);
this.state={showSignInPage:false}
}
toggleSignIn(){
this.setState({showSignInPage:!this.state.showSignInPage});
}
render(){
return(
<div>
{this.state.showSignInPage && <SignIn/>}
<button className='btn btn-danger' onClick={()=>this.toggleSignIn()}>Sign In</button>
</div>
</Router>
</div>
)
}
PS: Code I have not tested.
You can do in this way
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from "react-router-dom";
function SignIn() {
return "hello";
}
class App extends React.Component {
state = {
current: ""
};
toggle = () => {
this.setState({ current: this.state.current==''?"SignIn":"" })
};
render() {
return (
<Router>
<div>
{this.state.current == "SignIn" ? (
<Redirect to="/SignIn" />
) : (
<Redirect to="" />
)}
<button className="btn btn-danger" onClick={this.toggle}>
Sign In
</button>
<Switch>
<Route exact path="/SignIn" component={SignIn} />
</Switch>
</div>
</Router>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Resources