Search code examples
javascriptreactjsreact-hooksclassnameuse-state

Conditionally setting className based on a state variable in a React functional component


I'm trying to change the appearance of a button based on if that element exists in state. It is a multiple selection selection. So setAnswer is called, which calls addAnswer. I then want to set the className based on whether the element is in state but I'm just not getting it.

{question.values.map(answer => {
        return  <button className="buttons" key={answer} onClick={() => addAnswer(answer)}>
        {answer}</button>
})}
const addAnswer = (answer) => {
        let indexAnswer = answers.indexOf(answer)
        if (indexAnswer > -1) {
            setAnswer((answers) => answers.filter((a) => { 
                return a != answer }))}

        else setAnswer([...answers, answer])
    };

Solution

  • You can conditionally set a class like this

    {question.values.map(answer => {
            return (<button 
                     className={answers.indexOf(answer) === -1 ? 'class1' : 'class2'} 
                     key={answer} 
                     onClick={() => addAnswer(answer)}
                   >
                     {answer}
                  </button> );
    })}