I will share a few practices that I use when creating React components. Interested please under cat.
Condition setting
Take for example a button and its private states - size and color.
Usually in the code I come across something like this:
import React from 'react';
function Button({ size, skin, children }) {
return (
);
}
Its readability seems to be preserved, but what if we have even more states?
I thought it was much easier to collect all available states into a collection, where the key would be the name of the state, and the value would be the name of the class. Convenient viewing, convenient use. In addition, we will save on string operations.
So:
import React from 'react';
import classNames from 'classnames';
const SIZE_CLASSES = {
small: 'button_size_small',
medium: 'button_size_medium',
large: 'button_size_large',
};
const SKIN_CLASSES = {
accent: 'button_skin_accent',
primary: 'button_skin_primary',
};
function Button({ size, skin, children }) {
return (
);
}
For convenience of class assignment, I use the classnames utility .
Let us finally write another example.
import React from 'react';
const RESULT_IMAGES = {
1: '/img/medal_gold.svg',
2: '/img/medal_silver.svg',
3: '/img/medal_bronze.svg',
};
function Result({ position }) {
return (
Поздравляем! Вы на {position} месте!
);
}
Set tag by condition
Sometimes there is a need to expose a particular HTML tag or React component when rendering, depending on the condition. For example, of course, take our favorite button, because it perfectly demonstrates the problem. From the point of view of the UI, it usually looks like a button, but inside, depending on the situation, it can either be a tag