How to Add Active Class/State for Li Element in Reactjs

How to add active class/state for li element in ReactJS?

You can use classnames package https://github.com/JedWatson/classnames

import classNames from 'classnames';

return this.props.books.map((book) => {
return (
<li key={book.title}
className={classnames({'list-group-item':true, 'active': book.active})}
onClick={() => this.props.selectBook(book)}>
{book.title}
</li>
)
})

active class will affect only if book.active is true

//EDIT
you have to pass reducer_active_book property from your state through mapStateToProps

function mapStateToProps (state) {
return {
books: state.books,
reducer_active_book: state.reducer_active_book,
};

}

Now in render you can use this.

return this.props.books.map((book) => {
return (
<li key={book.title}
className={classnames({'list-group-item':true, 'active': this.props.reducer_active_book.id === book.id})}
onClick={() => this.props.selectBook(book)}>
{book.title}
</li>
)
})

Add active class to li items in react

You can track the active Li id and based on that add the active class.

import React, { useState } from "react";
import "./styles.css";

export default function App() {
const values = [
{ id: 1, text: "LI-1" },
{ id: 2, text: "LI-2" },
{ id: 3, text: "LI-3" },
{ id: 4, text: "LI-4" }
];
const [activeId, setActiveId] = useState();

return (
<div className="App">
<ul>
{values.map((val) => (
<li onClick={() => setActiveId(val.id)}>
{val.text} -- {activeId === val.id ? "Active" : "Inactive"}
</li>
))}
</ul>
</div>
);
}

Working Demo - https://codesandbox.io/s/naughty-sinoussi-bmy4p?file=/src/App.js:0-543

How to add active class on click in react js

A naive solution may be something like this. Don't forget to import 'useState' hook from React. You need to keep the track of the active item in the state.

const useStyles = makeStyles((theme) =>
createStyles({
link: {
textDecoration: 'none',
color: theme.palette.grey[900],
},
highlighted: {
backgroundColor: lighten(green[500], 0.5),
},
})
)

// eslint-disable-next-line
//@ts-nocheck
export const MenuItems: React.FC = () => {
const s = useStyles()
const [activeItemIndex, setActiveItemIndex] = useState(0)

return (
<div>
<Link to="/dashboard/proxies" className={s.link}>
<ListItem onClick={() => setActiveItemIndex(0)} className={activeItemIndex === 0 ? s.highlighted : null}>
<ListItemIcon>
<CloudDone />
</ListItemIcon>
<ListItemText primary="Proxies" />
</ListItem>
</Link>

<Link to="/dashboard/permissions" className={s.link}>
<ListItem onClick={() => setActiveItemIndex(1)} className={activeItemIndex === 1 ? s.highlighted : null}>
<ListItemIcon>
<VerifiedUser />
</ListItemIcon>
<ListItemText primary="Permissions" />
</ListItem>
</Link>

<Link to="/dashboard/test-helpers" className={classnames(s.link)}>
<ListItem onClick={() => setActiveItemIndex(2)} className={activeItemIndex === 2 ? s.highlighted : null}>
<ListItemIcon>
<Help />
</ListItemIcon>
<ListItemText primary="Test Helpers" />
</ListItem>
</Link>

<Link to="/dashboard/plans" className={s.link}>
<ListItem onClick={() => setActiveItemIndex(3)} className={activeItemIndex === 3 ? s.highlighted : null}>
<ListItemIcon>
<FormatListNumbered />
</ListItemIcon>
<ListItemText primary="Plans" />
</ListItem>
</Link>

<Link to="/dashboard/user-management" className={s.link}>
<ListItem onClick={() => setActiveItemIndex(4)} className={activeItemIndex === 4 ? s.highlighted : null}>
<ListItemIcon>
<Person />
</ListItemIcon>
<ListItemText primary="User Management" />
</ListItem>
</Link>

<Link to="/dashboard/activate-subscription" className={s.link}>
<ListItem onClick={() => setActiveItemIndex(5)} className={activeItemIndex === 5 ? s.highlighted : null}>
<ListItemIcon>
<PersonAdd />
</ListItemIcon>
<ListItemText primary="Activate Subscription" />
</ListItem>
</Link>

<Link to="/dashboard/user-plan-limits" className={s.link}>
<ListItem onClick={() => setActiveItemIndex(6)} className={activeItemIndex === 6 ? s.highlighted : null}>
<ListItemIcon>
<BarChartIcon />
</ListItemIcon>
<ListItemText primary="User Plan Limits" />
</ListItem>
</Link>
</div>
)
}

How to add active class to clicked item in ReactJS

Instead of trying to manipulate the DOM manually, you could keep a piece of state called e.g. activeLink that stores the id of the active link that you use that to apply the class to the active link in the render method.

Example

class SideNavbar extends React.Component {  state = {    links: [      {        id: 1,        name: "Link1",        to: "/cms",        className: "side_nav_item"      },      {        id: 2,        name: "Link2",        to: "/cms",        className: "side_nav_item"      },      {        id: 3,        name: "Link3",        to: "/cms",        className: "side_nav_item"      },      {        id: 4,        name: "Link4",        to: "/cms",        className: "side_nav_item"      }    ],    activeLink: null  };
handleClick = id => { this.setState({ activeLink: id }); };
render() { const { links, activeLink } = this.state;
return ( <div> {links.map(link => { return ( <div key={link.id}> <ul> <li onClick={() => this.handleClick(link.id)} className={ link.className + (link.id === activeLink ? " active_item" : "") } > {link.name} {link.id === activeLink && "active!"} </li> </ul> </div> ); })} </div> ); }}
ReactDOM.render(<SideNavbar />, document.getElementById("root"));
<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="root"></div>

How do I add an active class to a Link from React Router?

On the Link component you can now add activeClassName or set activeStyle.

These allow you to easily add styles to the currently active link.


Previously, you could create a custom component that works like a wrapper to Link with the following logic.

In a file called nav_link.js

import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';

class NavLink extends React.Component {
render() {
var isActive = this.context.router.route.location.pathname === this.props.to;
var className = isActive ? 'active' : '';

return(
<Link className={className} {...this.props}>
{this.props.children}
</Link>
);
}
}

NavLink.contextTypes = {
router: PropTypes.object
};

export default NavLink;

And use it as given below in your component:

...
import NavLink from "./nav_link";
.....

<nav>
<ul className="nav nav-pills pull-right">
<NavLink to="/">
<i className="glyphicon glyphicon-home"></i> <span>Home</span>
</NavLink>
<NavLink to="about">
<i className="glyphicon glyphicon-camera"></i> <span>About</span>
</NavLink>
</ul>
</nav>

Toggle Show/Hide `active` class on li's in react js

You can store the list of items in an array, and give each item object a clicked property like this.

let listItems = [
{ days: "Indefinitely", clicked: true, desc: "Indefinitely" },
{ days: 1, clicked: false, desc: "1 Day" },
{ days: 7, clicked: false, desc: "1 Week" },
{ days: 30, clicked: false, desc: "1 Month" },
{ days: 90, clicked: false, desc: "3 Months" },
{ days: 180, clicked: false, desc: "6 Months" }
];

This pattern will make your code more manageable. Also, it will make it easier to keep track of the "active" state of each item. Then create a list-iterating function to render the list-items with their corresponding days.

See working sandbox: https://codesandbox.io/s/pensive-ptolemy-oguo1

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

let listItems = [
{ days: 1, clicked: true, desc: "1 Day" },
{ days: 7, clicked: false, desc: "1 Week" },
{ days: 30, clicked: false, desc: "1 Month" },
{ days: 90, clicked: false, desc: "3 Months" },
{ days: 180, clicked: false, desc: "6 Months" }
];

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
listItems: listItems
};
}

handleOnClick = e => {
const { listItems } = this.state;

const updatedItems = listItems.map(item => {
if (item.days == e.target.value) {
return {
...item,
clicked: true
};
} else {
return {
...item,
clicked: false
};
}
});

this.setState({
listItems: updatedItems
});
};

createListItems = () => {
const { listItems } = this.state;

return listItems.map(item => {
return (
<li
onClick={this.handleOnClick}
className={item.clicked ? "active" : ""}
value={item.days}
>
{item.desc}
</li>
);
});
};

render() {
return <ul>{this.createListItems()}</ul>;
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The handleOnClick function will create an updated array of items. It will find the item selected and set clicked to true. All other items will have click set to false.

To determine what class each item will have, we use a ternary operator to check whether its own clicked property is true, which again can be changed by handleOnClick()

<li
onClick={this.handleOnClick}
className={item.clicked ? "active" : ""}
value={item.days}
>

How do you set an 'active' class in React and CSS?

There is actually a property of activeClassName in NavLink of react router.

It goes like this

Import { NavLink } from 'react-router-dom`
...

<NavLink exact activeClassName="your_active_css_classname" className="normal_css">Link name </NavLink>

Don't forget to add exact. Read more here: https://reacttraining.com/react-router/web/api/NavLink



Related Topics



Leave a reply



Submit