M
M
mishapsv2015-08-24 17:09:32
React
mishapsv, 2015-08-24 17:09:32

How to change class based on data array content in React?

There is some jason array and, based on its contents, the buttons should change color.
It seems to be simple, but it is not possible to implement.
Here I wrote through the ? operator, but more than one condition is not met. Yes, and it is not right, it must be endured.
If you take it out into a variable, which then substitute className = {variable}, then you get an array that needs to be sorted out again.
How would you write it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan Abdullaev, 2015-08-24
@mishapsv

If there is only one unique class, then the easiest way is through switch / case or reduce, but if there are many such classes, then rather than bypassing the array, it is better to access by key:

const statuses = {
'new_message': ["Новое сообщение", "btn-default"],
'pay': ["Оплатить", "btn-primary"]
...
};

className={statuses[box.btn1][1]}

Of course, you can leave Cyrillic statuses as keys, but this is less reliable, as it seems to me.
You can also store the button text and class not in an array, but in a nested object, for better readability
PS Added an example

P
Pavel Shvedov, 2015-08-24
@mmmaaak

Calculate the class name into a variable in the render method before calling return, using some kind of switch / case, and then just insert it into the template where necessary

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question