Home > Software engineering >  How to change the styles of Base Web Button component on click?
How to change the styles of Base Web Button component on click?

Time:01-17

I want to change the color and background color of the Base Web Button component on button click using React. How can I change the styles of the button on button click?

I tried to use $isSelected prop to detect clicking, but this didn't help me. Here is the code:

import { Button } from 'baseui/button'

...

<Button
  kind="secondary"
  size="compact"
  shape="pill"
  overrides={{
    BaseButton: {
      style: ({ $isSelected }) => ({
        color: $isSelected ? 'white' : 'black',
        backgroundColor: $isSelected ? 'black' : 'white',
      }),
    },
  }}
>
  Hello
</Button>

How can I handle it?

CodePudding user response:

You could create state that holds a true or false value and then style the button according to whether or not it has been clicked.

import * as React from "react";
import { Button } from "baseui/button";

export default () => {
  const [clicked, setClicked] = React.useState(false);
  return (
    <Button
      kind="secondary"
      size="compact"
      shape="pill"
      overrides={{
        BaseButton: {
          style: () => ({
            color: clicked ? "white" : "black",
            backgroundColor: clicked ? "black" : "white",
          }),
        },
      }}
      onClick={() => setClicked(!clicked)}
    >
      Hello
    </Button>
  );
};

Codesandbox : https://codesandbox.io/s/base-web-button-forked-gvxi2v?file=/src/example.js:513-523

Example forked directly from https://baseweb.design/components/button

If you wanted to create many of these buttons, you could extract the example into it's own component and render them out as many times as you want and they will each have their own clicked state.

  • Related