K
K
KononovD2019-10-22 16:36:21
JavaScript
KononovD, 2019-10-22 16:36:21

How to validate props?

Good day.
While studying React, I wrote a self-made carousel. And I thought that I was the most cunning and when I received props in componentWillMout I validated them, corrected them if necessary and wrote to the state. Only later I found out that writing props to the state is a bad idea.

The carousel can accept the following properties:

itemsToShow - сколько показывать слайдов в строке
itemsToScroll - по сколько слайдов перелистывать
height - высота карусели в пикселях ( если у нас слайдер картинок )
slides - собственно массив реакт-элементов
isLoop - перелистывание последнего элемента вернет в начало, перелистывание первого - в конец
isInfinity - можно листать в одну сторону бесконечно
speed - количество мс которые нужны для перелистывания
isArrowsShow - показывать ли стандартные стрелки
isDotsShow - показывать ли кнопки-точки
isVertical - листать влево/вправо или вверх/вниз
itemsInRow - аналог itemsToShow для вертикального слайдера
isAutoplay - автовоспроизвдение
stopAutoplayOnHover - останавливать ли автоплей по наведению мыши
isDraggable - будет ли листаться карусель мышкой/пальцем

All fields have default values
​​Validation was that the carousel would work correctly in any conditions.
For example:

если на вход пришел пустой массив/ не массив - в консоль кидаем варнинг и ничего не рисуем;
itemsToShow > slides.length ? itemsToShow = slides.length + варнинг в консоль;
itemsToScroll > itemsToShow ? itemsToScroll = itemsToShow + варнинг;
isInfinity ? slides = [ ...lastItems, ...slides, ...firstItems ] ( в начало добавляем слайды с конца, в конец из начала что бы реализовать бесконечный слайдер )

because of these validations, even if we tell the carousel "show 5" and give it 4 slides, it will show 4, not 4 and an empty space under the 5th slide. Changing props on the fly also works.
for example this line will work: itemsToShow={ innerWidth < 1700 ? innerWidth > 1000 ? 4 : 2 : 5 }
The carousel will change the number of slides displayed.
And because of all this logic, the code inside is scary, but the carousel itself works well.
Now I had to learn TS. As part of the training, I decided to rewrite my carousel on TS.
And going back to the beginning: writing props in the state is a bad tone, but I want to leave the data validation logic so that even if the content manager messes up in the admin panel with goods, the carousel behaved with dignity.
What is the right way to do this validation?
Thank you for reading all these letters :D

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question