DorinV
DorinV

Reputation: 322

React reusable button

React beginner here.
I have a react button component that I would like to reuse across my app.

This is my reusable button component:

const Button = (props) => {
  const [buttonPress, setbuttonPress] = useState('0');

  const click = () => {
    buttonPress !== '1' ? setbuttonPress('1') : setbuttonPress('0');
  }

  return (
    <Button className={buttonPress == '1' ? 'active' : ''} onClick={click}>
      {props.children}
    </Button>
  )
};

On click, it add an 'active' class to the component.
What I can't figure out is how to remove the class of the the previous 'active' button once I click on a different button.

<Button>Dog</Button>
<Button>Cat</Button>
<Button>Horse</Button>

Upvotes: 0

Views: 1773

Answers (3)

DorinV
DorinV

Reputation: 322

I've managed to solve it myself and it works as expected.
I used: useEffect, useCallback, useRef.

https://codesandbox.io/s/buttons-fc6xq?file=/src/index.js

Upvotes: 0

daniel93
daniel93

Reputation: 301

I misunderstood your question, but I think I was able to figure out.

You can check the example here.

In general, you will always need to keep the data inside the parent component and do a validation inside the child component, the data has to be accessible to every button.

Upvotes: 1

iamhuynq
iamhuynq

Reputation: 5529

You need to store index of pressed button in parent container and update it in function click. You can try this

const Button = (props) => {


return (
    <Button className={props.isPress == '1' ? 'active' : ''} onClick={props.click}>
      {props.children}
    </Button>
  )
};

// Parent container
const [buttonPress, setbuttonPress] = useState(null);

const click = index => {
   setbuttonPress(index) 
 }


const buttonList = ['Dog', 'Cat', 'Horse'].map((item, index) => <Button click={click(index)} isPress={buttonPress == index ? '1' : '0'}>{item}</Button>)

Upvotes: 0

Related Questions