How to add class ="active"

Asked

Viewed 42 times

0

inserir a descrição da imagem aqui

import React from 'react'
import { Link, withRouter } from 'react-router-dom'

const isActive= (history, path) => {
    if (history.location.pathname === path) return { active: 'active' }
    else return { color: 'pink' }
}

const App= ({ history }) => (
    <nav id="sidebar" className="fixed pt-3">
        <ul className="custom-scrollbar">
           
            <li><Link to="/dashboard" className={isActive(history, "/dashboard")}><span className="ti-home mr-3"></span>Home</Link></li>
           
        </ul>
    </nav>
)

ReactDOM.render(<App />, document.querySelector("#app"));
<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"></div>

1 answer

0


The problem is that you are returning an object to the attribute 'classname' of your element, the correct would be to return only the string 'active':

const isActive= (history, path) => {
  if (history.location.pathname === path) return 'active'
  else return 'pink'
}

I hope I’ve helped

  • It didn’t work Maycon

  • Try to take the keys from the classname: <li><Link to="/Dashboard" classname=isActive(history, "/Dashboard")><span classname="ti-home mr-3"></span>Home</Link></li>

  • If not, try it like this: <li><Link to="/Dashboard" classname={history.location.pathname == "/Dashboard" ? 'active' 'pink'}><span classname="ti-home mr-3"></span>Home</Link></li>

  • Now Sam! Thank you so much!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.