react button onClick redirect page - javascript

I am working on a web application using React and bootstrap. When it comes to applying button onClick, I'm having a hard time to have 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>
);
}
}

update:
React Router v6:
import React from 'react';
import { useNavigate } from "react-router-dom";
function LoginLayout() {
let navigate = useNavigate();
const routeChange = () =>{
let path = `newPath`;
navigate(path);
}
return (
<div className="app flex-row align-items-center">
<Container>
...
<Button color="primary" className="px-4"
onClick={routeChange}
>
Login
</Button>
...
</Container>
</div>
);
}}
React Router v5 with hooks:
import React from 'react';
import { useHistory } from "react-router-dom";
function LoginLayout() {
const history = useHistory();
const routeChange = () =>{
let path = `newPath`;
history.push(path);
}
return (
<div className="app flex-row align-items-center">
<Container>
...
<Row>
<Col xs="6">
<Button color="primary" className="px-4"
onClick={routeChange}
>
Login
</Button>
</Col>
<Col xs="6" className="text-right">
<Button color="link" className="px-0">Forgot password?</Button>
</Col>
</Row>
...
</Container>
</div>
);
}
export default LoginLayout;
with React Router v5:
import { useHistory } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink } from 'reactstrap';
class LoginLayout extends Component {
routeChange=()=> {
let path = `newPath`;
let history = useHistory();
history.push(path);
}
render() {
return (
<div className="app flex-row align-items-center">
<Container>
...
<Row>
<Col xs="6">
<Button color="primary" className="px-4"
onClick={this.routeChange}
>
Login
</Button>
</Col>
<Col xs="6" className="text-right">
<Button color="link" className="px-0">Forgot password?</Button>
</Col>
</Row>
...
</Container>
</div>
);
}
}
export default LoginLayout;
with React Router v4:
import { withRouter } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink } from 'reactstrap';
class LoginLayout extends Component {
constuctor() {
this.routeChange = this.routeChange.bind(this);
}
routeChange() {
let path = `newPath`;
this.props.history.push(path);
}
render() {
return (
<div className="app flex-row align-items-center">
<Container>
...
<Row>
<Col xs="6">
<Button color="primary" className="px-4"
onClick={this.routeChange}
>
Login
</Button>
</Col>
<Col xs="6" className="text-right">
<Button color="link" className="px-0">Forgot password?</Button>
</Col>
</Row>
...
</Container>
</div>
);
}
}
export default withRouter(LoginLayout);

Don't use a button as a link. Instead, use a link styled as a button.
<Link to="/signup" className="btn btn-primary">Sign up</Link>

React Router v5.1.2:
import { useHistory } from 'react-router-dom';
const App = () => {
const history = useHistory()
<i className="icon list arrow left"
onClick={() => {
history.goBack()
}}></i>
}

This can be done very simply, you don't need to use a different function or library for it.
onClick={event => window.location.href='/your-href'}

I was trying to find a way with Redirect but failed. Redirecting onClick is simpler than we think. Just place the following basic JavaScript within your onClick function, no monkey business:
window.location.href="pagelink"

First, import it:
import { useHistory } from 'react-router-dom';
Then, in function or class:
const history = useHistory();
Finally, you put it in the onClick function:
<Button onClick={()=> history.push("/mypage")}>Click me!</Button>

A very simple way to do this is by the following:
onClick={this.fun.bind(this)}
and for the function:
fun() {
this.props.history.push("/Home");
}
finlay you need to import withRouter:
import { withRouter } from 'react-router-dom';
and export it as:
export default withRouter (comp_name);

useHistory() from react-router-dom can fix your problem
import React from 'react';
import { useHistory } from "react-router-dom";
function NavigationDemo() {
const history = useHistory();
const navigateTo = () => history.push('/componentURL');//eg.history.push('/login');
return (
<div>
<button onClick={navigateTo} type="button" />
</div>
);
}
export default NavigationDemo;

If all above methods fails use something like this:
import React, { Component } from 'react';
import { Redirect } from "react-router";
export default class Reedirect extends Component {
state = {
redirect: false
}
redirectHandler = () => {
this.setState({ redirect: true })
this.renderRedirect();
}
renderRedirect = () => {
if (this.state.redirect) {
return <Redirect to='/' />
}
}
render() {
return (
<>
<button onClick={this.redirectHandler}>click me</button>
{this.renderRedirect()}
</>
)
}
}

if you want to redirect to a route on a Click event.
Just do this
In Functional Component
props.history.push('/link')
In Class Component
this.props.history.push('/link')
Example:
<button onClick={()=>{props.history.push('/link')}} >Press</button>
Tested on:
react-router-dom: 5.2.0,
react: 16.12.0

If you already created a class to define the properties of your Button (If you have a button class created already), and you want to call it in another class and link it to another page through a button you created in this new class, just import your "Button" (or the name of your button class) and use the code below:
import React , {useState} from 'react';
import {Button} from '../Button';
function Iworkforbutton() {
const [button] = useState(true);
return (
<div className='button-class'>
{button && <Button onClick={()=> window.location.href='/yourPath'}
I am Button </Button>
</div>
)
}
export default Iworkforbutton

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 on window, parse the URL you get, call this.setState(), and you have your own simple router, no library needed.
class LoginLayout extends Component {
constuctor() {
this.handlePageChange = this.handlePageChange.bind(this);
this.handleRouteChange = this.handleRouteChange.bind(this);
this.state = { page_number: 0 }
}
handlePageChange() {
window.location.hash = "#/my/target/url";
}
handleRouteChange(event) {
const destination = event.newURL;
// check the URL string, or whatever other condition, to determine
// how to set internal state.
if (some_condition) {
this.setState({ page_number: 1 });
}
}
componentDidMount() {
window.addEventListener('hashchange', this.handleRouteChange, false);
}
render() {
// #TODO: check this.state.page_number and render the correct page.
return (
<div className="app flex-row align-items-center">
<Container>
...
<Row>
<Col xs="6">
<Button
color="primary"
className="px-4"
onClick={this.handlePageChange}
>
Login
</Button>
</Col>
<Col xs="6" className="text-right">
<Button color="link" className="px-0">Forgot password </Button>
</Col>
</Row>
...
</Container>
</div>
);
}
}

With React Router v5.1:
import {useHistory} from 'react-router-dom';
import React, {Component} from 'react';
import {Button} from 'reactstrap';
.....
.....
export class yourComponent extends Component {
.....
componentDidMount() {
let history = useHistory;
.......
}
render() {
return(
.....
.....
<Button className="fooBarClass" onClick={() => history.back()}>Back</Button>
)
}
}

I was also having the trouble to route to a different view using navlink.
My implementation was as follows and works perfectly;
<NavLink tag='li'>
<div
onClick={() =>
this.props.history.push('/admin/my- settings')
}
>
<DropdownItem className='nav-item'>
Settings
</DropdownItem>
</div>
</NavLink>
Wrap it with a div, assign the onClick handler to the div. Use the history object to push a new view.

Make sure to import {Link} from "react-router-dom";
And just hyperlink instead of using a function.
import {Link} from "react-router-dom";
<Button>
<Link to="/yourRoute">Route Name</Link>
</Button>

Related

How to Convert a Class Component to a Functional Component in ReactJS

I always work with functional components as they give me more flexibility and i can use hooks with them. I have a drop down menu functionality that is coded using the class component. Now i need to convert this to a functional component as i need to do some backend work for some of the menu buttons, such as logout and name and so on.
I tried to convert it my self but it ended with always keeping to Modal open and giving me an error that reads " this.props.toggle is not a function at Dropdown.toggle" and it slowed down my website incredibly.
How can i make the below code equivalent to a functional component?
Class Component:
import React, { Component } from "react";
import PropTypes from 'prop-types';
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from "reactstrap";
import { withRouter, Link } from "react-router-dom";
//i18n
import { withTranslation } from "react-i18next";
import { connect } from "react-redux";
class ProfileMenu extends Component {
constructor(props) {
super(props)
this.state = {
menu: false,
name: "Admin",
}
this.toggle = this.toggle.bind(this)
}
toggle() {
this.setState(prevState => ({
menu: !prevState.menu,
}))
}
render() {
return (
<React.Fragment>
<Dropdown
isOpen={this.state.menu}
toggle={this.toggle}
className="d-inline-block"
>
<DropdownToggle
className="btn header-item"
id="page-header-user-dropdown"
tag="button"
>
<span className="d-none d-xl-inline-block ms-1">
{this.state.name}
</span>
<i className="mdi mdi-chevron-down d-none d-xl-inline-block" />
</DropdownToggle>
<DropdownMenu className="dropdown-menu-end">
<DropdownItem tag="a" href="/">
Dashboard
</DropdownItem>
<div className="dropdown-divider" />
<Link to="/logout" className="dropdown-item">
<i className="bx bx-power-off font-size-16 align-middle me-1 text-danger" />
<span>{this.props.t("Logout")}</span>
</Link>
</DropdownMenu>
</Dropdown>
</React.Fragment>
)
}
}
ProfileMenu.propTypes = {
t: PropTypes.any,
success: PropTypes.string
}
const mapStateToProps = state => {
const { success } = state.Profile
return { success }
}
export default withRouter(
connect(mapStateToProps, {})(withTranslation()(ProfileMenu))
)
Below code is how i tried to convert it
import React, { Component, useState, useEffect } from "react";
import PropTypes from 'prop-types';
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from "reactstrap";
import { withRouter, Link, useHistory } from "react-router-dom";
import firebase from "../../../firebase"
function ProfileMenu(){
const [isOpen, setIsOpen] = useState(false);
const history = useHistory();
const logout = () => {
firebase.auth().signOut().then(function() {
console.log("logged out")
history.push("/login");
}).catch(function(error) {
// An error happened.
console.log("didnt logout")
});
}
const openModal = () => {
setIsOpen(true);
};
const closeModal = () => {
setIsOpen(false);
};
return (
<React.Fragment>
<Dropdown
isOpen={isOpen}
onClick={openModal}
toggle={""}
className="d-inline-block"
>
<DropdownToggle
// onClick={openModal}
className="btn header-item"
id="page-header-user-dropdown"
tag="button"
>
<span className="d-none d-xl-inline-block ms-1">
{/* {this.state.name} */}
</span>
<i className="mdi mdi-chevron-down d-none d-xl-inline-block" />
</DropdownToggle>
<DropdownMenu className="dropdown-menu-end">
<DropdownItem tag="a" href="/">
Dashboard
</DropdownItem>
<div className="dropdown-divider" />
<button className="dropdown-item" onClick={logout}>
<i className="bx bx-power-off font-size-16 align-middle me-1 text-danger" />
<span>Logout</span>
</button>
</DropdownMenu>
</Dropdown>
</React.Fragment>
)
}
export default ProfileMenu
const ProfileMenu = (props) => {
const [name, setName] = useState('aaa'); // define and initialize name state
....
let myName = name; // call name state
....
let toggle = props.toggle; //call toggle props
}
I hope this will be helpful for you. Thanks.
You need to pass the toggle as function, you are instead passing string, also you can directly toggle state value, it will make the component re-render, try the following code and let me know if this helps.
Just for better visibility I am removing the class names, so that code looks clean.
You can also use the useContext instead of using redux.
import React, { useState } from "react";
import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from "reactstrap";
import { withRouter, useHistory } from "react-router-dom";
import firebase from "../../../firebase";
type Prop = {
name: string;
};
const ProfileMenu: React.FC<Prop> = ({ name }) => {
const [menu, setMenu] = useState(false);
const history = useHistory();
const logout = () => {
firebase
.auth()
.signOut()
.then(function () {
history.push("/login");
})
.catch(function (error) {
console.log("didnt logout");
});
};
return (
<Dropdown isOpen={menu} toggle={() => setMenu(!menu)} >
<DropdownToggle >
<span >{name}</span>
<i className="mdi mdi-chevron-down d-none d-xl-inline-block" />
</DropdownToggle>
<DropdownMenu >
<DropdownItem tag="a" href="/">
Dashboard
</DropdownItem>
<div className="dropdown-divider" />
<button onClick={logout}>
<i className="bx bx-power-off font-size-16 align-middle me-1 text-danger" />
<span>Logout</span>
</button>
</DropdownMenu>
</Dropdown>
);
};
export default withRouter(ProfileMenu);

React.js: How to convert class based component to functional?

I'm building an app using function based component. I found the sidebar menu template from Material Ui in classes and want to convert it to functional component. But after converting click button doesn't work. I've only changed the menu icon to another.
Any help will be appreciated.
Here is the default component in classes
import React from "react";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import Typography from "#material-ui/core/Typography";
import Button from "#material-ui/core/Button";
import IconButton from "#material-ui/core/IconButton";
import MenuIcon from "#material-ui/icons/Menu";
import { NavDrawer } from "./NavDrawer";
class NavBar extends React.Component {
constructor(props) {
super(props);
this.state = {
drawerOpened: false
};
}
toggleDrawer = booleanValue => () => {
this.setState({
drawerOpened: booleanValue
});
};
render() {
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<IconButton
color="secondary"
aria-label="Menu"
onClick={this.toggleDrawer(true)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit">
News
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
<NavDrawer
drawerOpened={this.state.drawerOpened}
toggleDrawer={this.toggleDrawer}
/>
</div>
);
}
}
export default NavBar
Here I'm trying to convert
import React, { useState } from 'react'
import AppBar from '#material-ui/core/AppBar'
import Toolbar from '#material-ui/core/Toolbar'
import Typography from '#material-ui/core/Typography'
import IconButton from '#material-ui/core/IconButton'
import NavDrawer from './NavDrawer'
import AddShoppingCartIcon from '#material-ui/icons/AddShoppingCart'
function NavBar(props) {
const [drawerOpened, setDrawerOpened] = useState(false)
const toggleDrawer = booleanValue => () => {
setDrawerOpened(booleanValue)
}
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<IconButton
aria-label="AddShoppingCartIcon"
onClick={() => toggleDrawer(true)}
>
<AddShoppingCartIcon style={{ fontSize: 30 }} color="secondary" />
</IconButton>
<Typography variant="h6" color="inherit"></Typography>
</Toolbar>
</AppBar>
<NavDrawer drawerOpened={drawerOpened} toggleDrawer={toggleDrawer} />
</div>
)
}
export default NavBar
Have a look at React hooks, there ae two approaches:
const [toggleDrawer, setToggleDrawer] = useState(false); // set variable
<button onClick={() => setToggleDrawer(!toggleDrawer}>
Of you can useEffect to perform some logic after the component is initially rendered, preventing a max error:
const toggleDrawer = false;
useEffect(() => { // update variable
checkDrawOpened(toggleDrawer)
}, toggleDrawer);]
With the one click
onClick={toggleDrawer} // use variable
You can do this instead for toggling actions.
const toggleDrawer = () => {
setDrawerOpened(!drawerOpened)
}
And in the return
onClick={toggleDrawer}
Your function is stacking. On onclick, you try to call function to call function. Just use the const instead.
on toggleDrawer const, you should set setDrawerOpened to whenever the opposite of value it is to get toggling effect.

Passing refs from Component to Component in React

So I am not sure if passing refs would be the best thing to do but it's kinda what I have set-out to do tell me if there is a better option..
So I am trying to have an onClick of a nav link, scroll down to the the div "contactForm".
App.js
import ContactForm from './components/ContactForm'
import ParllaxPage from './components/ParllaxPage'
import NavigationBar from './components/NavigationBar'
import React from 'react';
import './App.css';
const App = () => {
return (
< div cssClass="App" >
<body>
<span><NavigationBar /></span>
<ParllaxPage cssClass="parallax-wrapper" />
<ParllaxPage cssClass="parallax-wrapper parallax-pageOne" />
<ContactForm />
</body >
</div >
);
}
export default App;
I was trying to use forwardRef but I am not sure that I was doing it correctly so...
NavigationBar.js
import ContactForm from "./ContactForm";
import React, { useRef } from "react";
import App from "../App";
import { Nav, Navbar, Form, FormControl, Button } from "react-bootstrap";
const ContactFormRef = React.forwardRef((props, ref) => (
<ContactForm className="contactForm" ref={ref}>
{props.children}
</ContactForm>
));
const scrollToRef = (ref) => ref.current.scrollIntoView({ behavior: "smooth" });
const NavigationBar = () => {
const ref = React.forwardRef(ContactFormRef);
return (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">A1 Gutters</Navbar.Brand>
<Navbar.Toggle aria-controls="b casic-navbar-nav" />
<Nav className="mr-auto">
<Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#link">Link</Nav.Link>
<Nav.Link href="#" onClick={console.log(ref)}>
Contact
</Nav.Link>
</Nav>
</Navbar>
);
};
export default NavigationBar;
I don't think the other files really need to be shown, I am just trying to get the className out of the ContactForm component so I can scroll to it onClick.. I currently just have a console.log in the onClick.
Using Hooks will simplify here.
Have state variable for gotoContact and ref for contactRef
Add click handler for navigation link contact
Add useEffect hook and when ever use click on contact and ref is available (value in ref.current) then call the scroll to view)
import ContactForm from "./components/ContactForm";
import ParllaxPage from "./components/ParllaxPage";
import React, { useState, useEffect, useRef } from "react";
import "./App.css";
const NavigationBar = ({ onClickContact }) => {
return (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">A1 Gutters</Navbar.Brand>
<Navbar.Toggle aria-controls="b casic-navbar-nav" />
<Nav className="mr-auto">
<Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#link">Link</Nav.Link>
<Nav.Link href="#" onClick={() => onClickContact()}>
Contact
</Nav.Link>
</Nav>
</Navbar>
);
};
const App = () => {
const [gotoContact, setGotoContact] = useState(false);
const contactRef = useRef(null);
useEffect(() => {
if (gotoContact && contactRef.current) {
contactRef.current.scrollIntoView();
setGotoContact(false);
}
}, [gotoContact, contactRef.current]);
return (
<div cssClass="App">
<body>
<span>
<NavigationBar onClickContact={() => setGotoContact(true)} />
</span>
<ParllaxPage cssClass="parallax-wrapper" />
<ParllaxPage cssClass="parallax-wrapper parallax-pageOne" />
<div ref={contactRef}>
<ContactForm />
</div>
</body>
</div>
);
};
export default App;
You should identify the div "contactForm" with an id and have an anchor tag point to it:
<div id="contactForm"></div>
You can add scroll-behaviour: smooth to the body in CSS
No need to create a separate ContactFormRef wrapper. Simply use React.forwardRef in ContactForm itself. Those not passing a ref will not have to know it forwards refs.
Then, remember to further pass the ref received to a native element or use useImperativeHandle hook to add methods to it without passing it further down.
const ref = React.forwardRef(ContactFormRef)
This is wrong.
You should do it the same as with native components:
const ref = useRef()
return <ContactForm ref={ref} >
// etc
</ContactForm>
You are not rendering the ContactFormRef, so the reference points no nothing!
App.js should be like:
...
const App = () => {
const myNestedRefRef=React.useRef();
return (
...
<NavigationBar contactRef={myNestedRefRef}/>
...
<ContactForm ref={myNestedRefRef} />
...
);
}
...
ContactForm.js
...
function ContactForm=React.forwardRef((props, ref) => (
<form ref={ref}>
...
</form>
));
NavigationBar.js
const NavigationBar = ({contactRef}) => {
return (
...
<Nav.Link href="#" onClick={console.log(contactRef)}>
...
);
};
Consider that
If the <ContactForm/> hasn't been rendered yet, the ref will look like {current:null}

Reactjs Routing with history push but doent change the view only the URL

I'm working with a menu and this have a ListGroupItem and try to redirect another component with history push but only change in the url! This url works but it doesn't change the view, I have to press enter to make this work.
I'm new with react, especially with the router, and I'm feeling lost with this. Thanks for any help.
This is my App.js
import React, { Component } from 'react';
import './css/App.css';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import Prueba from './Prueba';
import Menu from './header/Menu';
class App extends Component {
toggle(menu) {
if (this.state.collapse == menu){
this.setState({ collapse: false });
}else {
this.setState({ collapse: menu });
}
}
render() {
return (
<BrowserRouter>
<Menu/>
<Prueba/>
</BrowserRouter>
);
}
}
export default App;
This is my another component with name Prueba.js
import React, { Component } from 'react';
import './css/App.css';
import { BrowserRouter, Route,Link} from 'react-router-dom';
import { ListGroup, ListGroupItem,Collapse, Container, CardBody, Card, Row, Col} from 'reactstrap';
import Pais from './UbicacionGeneral/Pais';
import { withRouter } from 'react-router';
class Prueba extends React.Component{
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = { collapse: false };
this.routeChange = this.routeChange.bind(this);
}
routeChange() {
this.props.history.push('Pais');
}
componentDidUpdate(){
}
toggle(menu) {
if (this.state.collapse == menu){
this.setState({ collapse: false });
}else {
this.setState({ collapse: menu });
}
}
render() {
return (
<BrowserRouter>
<div className="App text-center">
<Row>
<Col md="2">
<ListGroup className="List-Principal">
<ListGroupItem className="List-Principal-Item " onClick={() => this.toggle("ubicacion")} > Ubicacion General </ListGroupItem>
<Collapse isOpen={this.state.collapse == "ubicacion"}>
<ListGroup>
<ListGroupItem onClick={this.routeChange} > Pais </ListGroupItem>
<ListGroupItem > Estado </ListGroupItem>
<ListGroupItem > Ciudad </ListGroupItem>
</ListGroup>
</Collapse>
<ListGroupItem className="List-Principal-Item tex-center"
onClick={() => this.toggle("almacen")} > Almacen </ListGroupItem>
<Collapse isOpen={this.state.collapse == "almacen"}>
<ListGroup>
<ListGroupItem > Crear - Modificar </ListGroupItem>
<ListGroupItem > Verificar Stock </ListGroupItem>
<ListGroupItem > Movimientos </ListGroupItem>
</ListGroup>
</Collapse>
</ListGroup>
</Col>
<Col md="10">
<Container>
<Route path="/Pais" component={Pais} />
</Container>
</Col>
</Row>
</div>
</BrowserRouter>
);
}
}
export default withRouter(Prueba);
Finally this is the component I want to see with the history push, named Pais.
Pais.js
import React, { Component } from 'react';
import { ListGroup, ListGroupItem,Collapse, Container, CardBody, Card, Row, Col} from 'reactstrap';
import { Alert } from 'reactstrap';
import { withRouter } from 'react-router-dom';
class Pais extends Component {
render() {
return (
<div>
<Alert color="primary">
This is a primary alert — check it out!
</Alert>
<Alert color="secondary">
This is a secondary alert — check it out!
</Alert>
<Alert color="success">
This is a success alert — check it out!
</Alert>
<Alert color="danger">
This is a danger alert — check it out!
</Alert>
<Alert color="warning">
This is a warning alert — check it out!
</Alert>
<Alert color="info">
This is a info alert — check it out!
</Alert>
<Alert color="light">
This is a light alert — check it out!
</Alert>
<Alert color="dark">
This is a dark alert — check it out!
</Alert>
</div>
);
}
}
export default withRouter (Pais);
There are several parts that are incorrect.
First of all, you shouldn't use BrowserRouter in Prueba.js. There should be only one BrowserRouter.
Also, you either put Route inside BrowserRouter or Switch.
As you didn't configure routes properly using BrowserRouter, Switch and Route, url changes but that doesn't reflect to your React App.

ReactJS - onClick to call a component that fadeIn

New web dev I found some nice pure HTML/JQuery template.
https://www.creative-tim.com/
I have to do an app with React and I would like to implement to login modal template on this web site.
https://www.creative-tim.com/product/login-and-register-modal
I'm not sure about the approch I have to make to be able to convert this to React.
I have to handle the onClick on the buttons and make the modal appear.
How can I load the component Modal by change the CSS like the way they do with JQuery ?
import React, { Component } from 'react';
import { Grid, Row, Col, Button } from 'react-bootstrap/lib'
import './Login.css'
import LoginModal from '../LoginModal/LoginModal'
class Login extends Component {
openLoginModal(){
console.log('openLoginModal');
// showLoginForm();
}
openRegisterModal(){
console.log('openRegisterModal');
// showRegisterForm();
}
render() {
return (
<Grid>
<Row>
<Col sm={4}></Col>
<Col sm={4}>
<Button bsClass="btn big-login" data-toggle="modal" onClick={this.openLoginModal}>Log In</Button>
<Button bsClass="btn big-register" data-toggle="modal" onClick={this.openRegisterModal}>Register</Button>
</Col>
<Col sm={4}></Col>
</Row>
<LoginModal />
</Grid>
)
}
}
export default Login
In React you don't need to use CSS to show and hide the modal. You can just use an inline conditional expression with JSX.
first you need to build a RegisterModal...
...Then
import React, { Component } from 'react';
import { Grid, Row, Col, Button } from 'react-bootstrap/lib'
import './Login.css'
import LoginModal from '../LoginModal/LoginModal'
import RegisterModal from '../RegisterModal/RegisterModal';
class Login extends Component {
constructor() {
super();
// create state properties to record open/close for each modal
this.state = {
loginOpen: false,
registerOpen: false
};
}
// toggle your state
openLoginModal(){
this.setState({ loginOpen: true, registerOpen: false });
}
openRegisterModal(){
this.setState({ loginOpen: false, registerOpen: true });
}
render() {
// `{ true && <div /> }` will render div if true
return (
<Grid>
<Row>
<Col sm={4}></Col>
<Col sm={4}>
<Button bsClass="btn big-login" data-toggle="modal" onClick={this.openLoginModal}>Log In</Button>
<Button bsClass="btn big-register" data-toggle="modal" onClick={this.openRegisterModal}>Register</Button>
</Col>
<Col sm={4}></Col>
</Row>
{ this.state.loginOpen &&
<LoginModal />
}
{ this.state.registerOpen &&
<RegisterModal />
}
</Grid>
)
}
}

Categories