'Logout button doesn't respond when clicked in React.js

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?



Solution 1:[1]

Just use onClick event, not onChange.

Good luck!

Solution 2:[2]

<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.

Solution 3:[3]

Try using

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 true_k
Solution 2 Sojib
Solution 3 Rakesh Shrestha