Jon
Jon

Reputation: 313

How to use OR Condition in Ternary operator in ReactJS

I am new to ReactJS . Actually I am working on Menues in ReactJS project . Here I have implemented logic for active menu For example if user is on page 2 it will show Active Menu for User . Currently , I am using window.location.pathname for comparing the user page but I want with both . I mean if user click on menu I will compare it with state value or if user is on page I will compare it with window.location.pathname . I am new to ReactJS , please expert help me . I will also provide code if someone is not fully understand on my problem statement . Sorry , If I made mistake in English Grammar because I am not native speaker . Thanks

Code

    class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

Upvotes: 0

Views: 9975

Answers (3)

bitsapien
bitsapien

Reputation: 1833

The use of a state called activeMenu is complicating your component unnecessarily. You should consider simplifying it in the following manner:

import React, { Component } from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { Icon } from 'semantic-ui-react';
import Header from '../header/header';


// Style Components
import {LeftMenuStyle} from '../appStyles/appStyles'


class LeftMenuList extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const menus = [
      {
        name: 'dashboard',
        icon: 'dashboard',
      },
      {
        name: 'organizations',
        icon: 'sitemap',
      },
      {
        name: 'contacts',
        icon: 'phone square',
    },

      {
        name: 'products',
        icon: 'shopping cart',
      },
      {
        name: 'sales',
        icon: 'credit card',
      },
      {
        name: 'purchases',
        icon: 'shopping bag',
      },
      {
        name: 'shipments',
        icon: 'shipping',
      },
      {
        name: 'everything',
        icon: 'ald',
      },
      {
        name: 'reports',
        icon: 'chart line',
      },
      {
        name: 'logout',
        icon: 'arrow right',
      }

    ];

    return (
      <div>
        <Header />
        <LeftMenuStyle>
        <div className="left-menus">
          {menus.map(item => {
              return (
                <NavLink to={"/"+item.name} name={item.name} key={item.name}
                  className='menu'
                  activeClassName='active'
                  >
                  <Icon name={item.icon} size="large"/>
                  <span>{item.name}</span>
                </NavLink>
              )
          })}
        </div>
        </LeftMenuStyle>
      </div>
    );
  }
}

export default withRouter(LeftMenuList);

The Link component from react-router-dom would automatically change your path to the active path and consequently your active link would acquire the active class name.

Here you see that we wrap the component with a WithRouter function, this gives you the react-router specific path object which you can use to determine your current path.

Upvotes: 1

maazadeeb
maazadeeb

Reputation: 6112

Looks like you're trying to redo the functionality of NavLink. You could change your JSX code to below and get the required behaviour

<NavLink
  to={"/" + item.name}
  name={item.name}
  key={item.name}
  className="menu"
  activeClassName="active"
  onClick={() => this.setState({ activeMenu: item.name })}
>
  <span> {item.name} </span> |
</NavLink>

I'm using activeClassName to add the active class when the item is active. Working codesandbox.

Upvotes: 1

Ishwar Patil
Ishwar Patil

Reputation: 1736

Check this out. You can write condition as pathName === item.name || this.state.activeMenu === item.name ? 'menu active' : 'menu'

Note: The color of active link is set to red in below example.

class LeftMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeMenu: 'dashboard'
    };
  }

  render() {
    const menus = [
      {
        name: 'dashboard',
        icon: 'dashboard',
      },
      {
        name: 'organizations',
        icon: 'sitemap',
      },
      {
        name: 'contacts',
        icon: 'phone square',
    },

      {
        name: 'products',
        icon: 'shopping cart',
      },
      {
        name: 'sales',
        icon: 'credit card',
      },
      {
        name: 'purchases',
        icon: 'shopping bag',
      },
      {
        name: 'shipments',
        icon: 'shipping',
      },
      {
        name: 'everything',
        icon: 'ald',
      },
      {
        name: 'reports',
        icon: 'chart line',
      },
      {
        name: 'logout',
        icon: 'arrow right',
      }

    ];

    const pathName='dashboard';
    return (
      <div>
        <div className="left-menus">
          {menus.map(item => {
              return (
                <a to={"/"+item.name} name={item.name} key={item.name}
                  className={pathName === item.name || this.state.activeMenu === item.name ? 'menu active' : 'menu' }
                  onClick={() => this.setState({activeMenu: item.name})}
                  >
                  <span>  {item.name}  </span>
                  <br/>
                </a>
              )
          })}
        </div>
      </div>
    );
  }
}

ReactDOM.render(<LeftMenu />, document.getElementById("app_root"));
.menu {
  color: black;
  cursor: pointer;
}

.menu.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app_root"></div>

Upvotes: 1

Related Questions