'changing the variant of the Button onClick MUI

I want to change the variant of the Button component whenever it gets clicked, from 'outlined' to 'contained':

<Button variant='outlined'>Click me to change my variant to contained</Button>

Is that possible in MUI? using React refs? or how can I achieve this?



Solution 1:[1]

you can achieve it like this:

import React, { useState } from 'react';


    function App() {
      const [currentButtonVariant, setCurrentButtonVariant] = useState('outlined');
    
      const handleButtonVariantChange = () => {
        if (currentButtonVariant === 'outlined') {
          setCurrentButtonVariant('contained');
        }
        else {
          setCurrentButtonVariant('outlined');
        }
      }
    
      return (
        <div className="App">
            <Button variant={currentButtonVariant} onClick={handleButtonVariantChange}>Click me to change my variant to contained</Button>
        </div>
      );
    }

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 Wings