Home > Software engineering >  Logout button doesn't respond when clicked in React.js
Logout button doesn't respond when clicked in React.js

Time:04-11

I've made a simple logout button/function that I'm almost certain that should work but it doesn't and there isn't any error either. Here's my code:

import {Link} from 'react-router-dom';
import { CredentialsContext } from '../App';
import Todos from '../Components/Todos';

export default function Welcome() {
  const [credentials, setCredentials] = useContext(CredentialsContext)
  const logout = () => {
    setCredentials(null);
  }
  return (
    <div>
        {credentials && <button onChange={logout}>Logout</button>}
        <h1>Welcome {credentials && credentials.username}</h1>
        {!credentials &&<Link to="/register">Register</Link>}
        <br/>
        {!credentials &&<Link to="/login">Login</Link>}
        {credentials && <Todos/>}
    </div>
  )
}

Any chance my backend might have something to do with it?

CodePudding user response:

<button onChange={logout}>Logout</button>

Why you are using onChange event in button?

<button onClick={logout}>Logout</button>

Use onClick event instead of onChange event.

CodePudding user response:

Try using

{credentials && <button onChange={()=>{logout}}>Logout</button>}

or {credentials && <button onClick={()=>{logout}}>Logout</button>}

CodePudding user response:

Just use onClick event, not onChange.

Good luck!

CodePudding user response:

You can try this: Add the code below in-between script tags

<script>
logout() {
    localStorage.clear();
    window.location.href = '/';
}
</script>

change HTML to this 
{credentials && <button onclick="logout()" onChange={logout}>Logout</button>}

When logout button is clicked, localstorage is cleared and it auto logs off from the website.

  • Related