0

I have two navigation buttons (light version, and dark version) that I want to render on certain pages.

I tried setting the state in the constructor, and generating the link to the images based on the path of the page, but sometimes the wrong link to the image will generated. It seems as though it's getting the state based on the first page that was ever generated. For example, if "home" is supposed to have the light version of the button any other link I click will generate the light version of the logo, unless I refresh. If "about" is supposed to have the dark version of the logo, all other pages I click through will have the dark version, unless I refresh.

Why won't it generate properly while naturally clicking around and navigating through the different pages?

MenuButton.js

import React, { Component } from 'react'; 

export default class MenuButton extends Component {

  constructor() {
    super();
    this.state = {
      logo_url: ''
    }
  }

  componentDidMount() {
    let currentPath = window.location.pathname;

    if (!currentPath.includes('about') && !currentPath.includes('news') 
        && !currentPath.includes('work')) {
          this.setState({ logo_url: `${require('../../assets/nav/logo-light.svg')}` });
    } else {
      this.setState({ logo_url: `${require('../../assets/nav/logo-dark.svg')}` });
    }
  }

  render() {
    return (
      <div className="menu-btn--cntr">
        <img src={this.state.logo_url} />
      </div>
    )
  }
}
bluebrooklynbrim
  • 277
  • 4
  • 19

1 Answers1

1

You don't need to use state and life cycle.

You can try something like below -

import React, { Component } from 'react'; 

export default class MenuButton extends Component {

  constructor() {
    super();
    this.state = {
      logo_url: ''
    }
  }

  getButton() {
    let currentPath = window.location.pathname;
    let btnUrl = ''; // or set some default 
    if (!currentPath.includes('about') && !currentPath.includes('news') 
        && !currentPath.includes('work')) {
          // this.setState({ logo_url: `${require('../../assets/nav/logo-light.svg')}` });
            btnUrl = `${require('../../assets/nav/logo-light.svg')}`;
    } else {
      // this.setState({ logo_url: `${require('../../assets/nav/logo-dark.svg')}` });
      btnUrl = `${require('../../assets/nav/logo-light.svg')}`;
    }
    return btnUrl;
  }

  render() {
    const btnUrl = this.getButton();
    return (
      <div className="menu-btn--cntr">
        <img src={btnUrl} />
      </div>
    )
  }
}
Chotala Paresh
  • 566
  • 4
  • 12
kag
  • 144
  • 1
  • 13