0

If Im running my site through Home page it works good because starting state is set to false so button renders properly. My problem is that when I go directly to /login page i want to set state to true. Could anyone give me idea?

import React from 'react'
import { NavLink } from 'react-router-dom'
import '../styles/NavBar.css'
import logo from '../res/pwrlogo.png'


class NavBar extends React.Component {
    constructor(props) {
        super(props);
        this.loginPageOn = this.loginPageOn.bind(this);
        this.loginPageOff = this.loginPageOff.bind(this);
        this.state = { isloginPageOn: false }

    }


    loginPageOn() {
        this.setState({ isloginPageOn: true })
        console.log(this.state)
    }

    loginPageOff() {
        this.setState({ isloginPageOn: false })
        console.log(this.state)
    }


    render() {
        const isloginPageOn = this.state.isloginPageOn;

        let navlink;

        if (isloginPageOn) {
            navlink = <NavLink to='/' className="rightButton" onClick={this.loginPageOff}>Strona główna</NavLink>
        }
        else {

            navlink = <NavLink to='/login' className="rightButton" onClick={this.loginPageOn}>Logowanie</NavLink>
        }

        return (
            <div className="topnav">
                <img src={logo} alt="Logo" />
                {navlink}

            </div>)
    }
Nexog
  • 3
  • 1

1 Answers1

0

You can use location object and get current pathname on component load using componentWillReceiveProps (depending on your react version). So you will have something like this:

componentWillReceiveProps(nextProps) {
  if (this.props.location.pathname !== nextProps.location.pathname) {
    if (nextProps.location.pathname === '/login') {
      this.setState({ isloginPageOn: true });
    } else {
      this.setState({ isloginPageOn: false });
    }
  }
}

This way you won't need the functions loginPageOn and loginPageOff because state will be updated from componentWillReceiveProps.

There are different ways to access location object depending on your react-router version. You can read more about that here.

gergana
  • 681
  • 6
  • 11