Home > Software design >  ReactJS Onclick function not working with href
ReactJS Onclick function not working with href

Time:10-16

href is not working when I click the element with an onClick function with it

function Sidebar(){

    function toggleChange(e){
    e.preventDefault();
    const el = document.getElementById("dashboard-button");
    el.className="nav-link";
        }
 return(
                    <div>
                      <li className="nav-item active">
                        <a className='nav-link collapsed' id="dashboard-button" 
                         href='./dashboardpage' onClick={toggleChange}>
                        <i ></i>
                        <span>Dashboard</span>
                        </a>
                        </li>
                       </div>
                      )

CodePudding user response:

You need to add in toggleChange function history.push('/dashboardpage'); For more detail https://v5.reactrouter.com/web/api/Hooks/usehistory

Otherwise you can remove e.preventDefault();

CodePudding user response:

You can use e.preventDefault() The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

  • Related