I am working on web application using React and bootstrap. When it comes to applying button onClick, it takes me hard time to let my page being redirect to another. if after a href , I cannot go the another page.
So would you please tell me is there any need for using react-navigation or other to navigate the page using Button onClick ?
import React, { Component } from 'react';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink } from 'reactstrap';
class LoginLayout extends Component {
render() {
return (
<div className="app flex-row align-items-center">
<Container>
...
<Row>
<Col xs="6">
<Button color="primary" className="px-4">
Login
</Button>
</Col>
<Col xs="6" className="text-right">
<Button color="link" className="px-0">Forgot password?</Button>
</Col>
</Row>
...
</Container>
</div>
);
}
}
A simple click handler on the button, and setting
window.location.hash
will do the trick, assuming that your destination is also within the app.You can listen to the
hashchange
event onwindow
, parse the URL you get, callthis.setState()
, and you have your own simple router, no library needed.I was also having the trouble to route to a different view using navlink.
My implementation was as follows and works perfectly;
Wrap it with a div, assign the onClick handler to the div. Use the history object to push a new view.
First, import it:
Then, in function or class:
Finally, you put it in the
onClick
function:A very simple way to do this is by the following:
and for the function:
finlay you need to import withRouter:
and export it as:
useHistory()
fromreact-router-dom
can fix your problemWith React Router v5.1: