invrt
invrt

Reputation: 709

Styled components, toggle state with mapped buttons

I have 4 buttons that are generated through my map function. When I click the button I would like the style to be applied to only that 1 button. Right now the style is being applied to all buttons.

Where am I going wrong?

const MultiChoiceQuestions = props => {
  const { multiChoiceArray, handleClick, inputValue, updateInputValue } = props
  const [active, setActive] = useState(false)
  console.log('state', active)
  // () => handleClick(questionChoice)
  return (
    <ButtonContainer>
      {multiChoiceArray.map(questionChoice => {
        return (
          <Button
            active={active}
            type="button"
            key={questionChoice.id}
            onClick={() => setActive(!active)}
          >
            {questionChoice.text}
          </Button>
        )
      })}
    </ButtonContainer>
  )
}

const Button = styled.button`
  height: 3rem;
  width: 20rem;
  border-style: solid;
  border-width: 1px;
  border-color: #c7c7c76b;
  background-color: ${props => (props.active ? 'green' : 'white')};
  cursor: pointer;
  -webkit-appearance: none;
  -moz-appearance: none;
  border-radius: 6px;
  transition: background 250ms ease-in-out, transform 150ms ease;
  font-weight: 400;
  &:hover {
    background-color: #ff00006b;
    transform: scale(1.25);
    font-weight: 800;
    border: none;
  }
`

Upvotes: 0

Views: 253

Answers (2)

Alexander
Alexander

Reputation: 1400

You need to keep the active button's ID in the state. And when rendering buttons, check if the button’s ID is equal to the active ID state. It will be an analogue of radio buttons.

const MultiChoiceQuestions = props => {
  const { multiChoiceArray, handleClick, inputValue, updateInputValue } = props
  const [activeId, setActiveId] = useState()
  console.log('state', active)
  // () => handleClick(questionChoice)
  return (
    <ButtonContainer>
      {multiChoiceArray.map(questionChoice => {
        return (
          <Button
            active={questionChoice.id === activeId}
            type="button"
            key={questionChoice.id}
            onClick={() => setActive(questionChoice.id)}
          >
            {questionChoice.text}
          </Button>
        )
      })}
    </ButtonContainer>
  )
}

Upvotes: 1

Mike P.
Mike P.

Reputation: 251

You have only one state variable for all the buttons. You can either create a new button component (with its own state) or create an array with four states.

Upvotes: 0

Related Questions