React — создание динамических форм и модальных компонентов
Начнем с создания следующей структуры папок в директории component :
Сначала мы собираемся изменить файл SuccessModal.js :
Этот код довольно прост. Мы используем компоненты react-bootstrap для модального внутри функционального компонента. Через объект props мы отправляем разные параметры нашему модальному окну и одно событие. Это событие закроет модальное окно после того, как мы нажмем кнопку.
Таким же образом изменим файл ErrorModal.js :
Далее, нам нужно изменить файл ModalStyles.css :
Теперь у нас есть модальные компоненты, которые мы можем использовать для создания, обновления или любого другого компонента. Мы намеренно создали два модальных компонента, хотя они почти одинаковы, потому что их гораздо легче читать, когда мы используем модальные компоненты внутри родительских компонентов. Вы можете сразу понять, какова цель модального окна, просто взглянув на его имя.
Создание конфигурации для элементов ввода
Внутри папки src мы собираемся создать папку Utility и внутри нее новый файл InputConfiguration.js . В этом файле мы собираемся сохранить все наши настройки конфигурации для элементов ввода (имя, адрес, дата рождения), которые мы собираемся использовать в формах добавления и редактирования.
Мы уже установили библиотеку моментов в предыдущем посте, но если вы еще этого не сделали, сделайте это (она нужна нам для элемента управления datepicker) с помощью следующей команды:
Теперь давайте изменим файл InputConfiguration.js :
Позже, в нашем компоненте create , мы собираемся преобразовать этот объект в массив объектов и отправить его компоненту Input для создания всех полей ввода, которые нам нужны в форме. Этот массив будет состоять из объектов (пар ключ-значение), где ключом будет имя, адрес или дата рождения (свойства из указанного выше объекта), а значение будет полной частью конфигурации того же объекта. (тип, значение, элемент…).
Динамическое создание входных элементов
Первое, что нам нужно сделать, это установить библиотеку react-datepicker , потому что мы собираемся использовать ее для элемента управления датой рождения.
В папке src создадим папку UI . Внутри нее мы собираемся создать новую папку Input и внутри нее файлы Input.js и Input.css :
Файл Input.js будет функциональным компонентом, поэтому давайте изменим его соответствующим образом:
На данный момент мы просто импортируем все необходимые нам ресурсы, инициализируем поле ввода и сообщение об ошибке и установим значение для этого сообщения, если элемент управления недействителен, если он должен быть проверен и если сделать его активным. Мы не хотим отображать ошибку, если пользователь вообще не поместил курсор мыши внутри этого компонента. Далее, мы возвращаем это поле ввода (которое на данный момент имеет значение NULL) родительскому компоненту.
Под оператором if и над блоком return мы собираемся добавить код для заполнения свойства inputField :
Итак, мы переключаемся между типом элемента и, если это тип ввода, мы создаем поле ввода со всеми необходимыми ему свойствами и событиями. То же самое мы делаем для элемента управления datePicker. Для наших форм этих двух типов ввода будет достаточно, но если вам для любого из ваших проектов нужно больше элементов управления, просто добавьте дополнительный оператор case.
Осталось изменить файл Input.css :
В этом классе мы переопределяем некоторые из собственных классов datePicker и добавляем один настраиваемый класс ( .datePickerControl ).
Вот и все, теперь мы можем перейти к компоненту CreateOwner .
Компонент CreateOwner
В папке containers , а затем внутри папки Owner создайте новую папку и назовите ее CreateOwner . Внутри создайте новый файл CreateOwner.js .
Приступим к редактированию этого файла:
В приведенном выше коде мы импортируем все необходимые компоненты react-bootstrap и функцию returnInputConfiguration из файла InputConfiguration.js . Этот компонент является компонентом класса или компонентом с отслеживанием состояния, и в хуке жизненного цикла componentWillMount мы обновляем наше локальное состояние с учетом всей конфигурации формы. Хук compnentWillMount сработает непосредственно перед установкой компонента.
Давайте добавим еще одну строку кода между блоками render и return :
В функции convertStateToArrayOfFormObjects мы хотим преобразовать объект ownerForm в массив объектов, чтобы отправить его компоненту Input . Итак, давайте добавим эту функцию в отдельный файл.
Внутри папки Utility создайте новый файл FormUtility.js . Измените этот файл, добавив функцию преобразования объекта:
Теперь нам нужно импортировать эту функцию в файл CreateOwner.js :
У нас будет больше действий внутри файла FormUtility.js , поэтому мы импортируем все эти действия в компонент CreateOwner.js .
Мы заполнили formElementsArray , поэтому давайте воспользуемся им для отправки всех свойств компоненту Input .
Объект конфигурации элементов формы
Давайте добавим этот код в тег Well :
В этом коде мы перебираем все объекты (входные конфигурации) внутри formElementsArray и возвращаем компонент Input со всеми необходимыми свойствами и событиями, которые ему требуются. Существует функция handleChangeEvent , и мы собираемся создать эту функцию, чтобы включить проверку и двустороннюю привязку. Но об этом чуть позже.
Чтобы увидеть результат наших текущих действий, давайте изменим файл App.js , добавив другой маршрут к компоненту CreateOwner ниже маршрута OwnerDetails . Не следует забывать и об операторе импорта:
Если мы перейдем на страницу CreateOwner , мы увидим такой результат:
Мы создали элементы управления, но пока ничего не можем с ними сделать. Но как только мы реализуем функцию handleChangeEvent , мы сможем изменять и проверять наши входные данные.
Завершение компонента CreateOwner
Давайте добавим кнопки к нашему компоненту, чтобы завершить создание компонента.
Внутри тега Form и ниже тега
добавьте этот код:
Мы добавляем две кнопки, и кнопка «Создать» неактивна, пока форма недействительна.
Теперь наша форма выглядит так:
Все работает как надо.
Заключение
Прочитав этот пост, вы узнали:
- Как использовать модальные элементы Bootstrap для создания повторно используемых компонентов модального окна.
- Использовать простой объект конфигурации для создания формы и как передать его в массив объектов.
- Как передать массив конфигурации с помощью простого кода JSX в представление формы.
Спасибо, что прочитали статью, и я надеюсь, что вы нашли в ней что-то полезное.
В следующей части серии мы узнаем, как проверять наши элементы ввода. Кроме того, мы собираемся использовать CreateComponent для отправки запроса POST на сервер .NET Core Web API.
React best practice to create modal window
How to create a modal window using React? By modal window I mean a frame which overlays with the content of a page. I want it to open up using a button on the webpage, be able to close it by clicking outside area and it will contain a form which user will fill and submit.
Does React have some production ready library for this task, or should I implement it using css? Also in the case of container/representational component pattern, should I nest the modal component inside the container component of modal opening component or inside the modal opening component itself?
2 Answers 2
1 — If you want to write a generic modal component in React, the only thing that your react modal component should do is to give a consistent view such as containing an overlay, setting positioning values and all common behaviour etc. The interaction decisions depends on how you proceed along the application. For example, in this kind of approach I mention as (1), fits better with using Flux. Basically you have a store, and collect all component state related data in it, and the ui states are managed by props passed to your component instead of calling setState in order to change the state of your component. In addition, this gives you the ability to change the component’s state outside of the component. Let me clear myself with an example:
And a style file like :
And you can use it as :
This modal design only gives the proper view and basic controls of a modal, and configuration is all up to your usages. If your application logic pretty much similar in other usages of modals, then you can add them into the modal component yourself.
How to create an efficient Modal component in React using Hooks and Portals
Modal is a common UX element. A modal is a dialog box/popup window that is displayed on top of the current page. You must have used pop-ups and notifications for your website. For some people pop-ups are really annoying if it doesn’t behave as it should. It must have good UI/UX.
In this article we’re going to create an efficient Modal component from scratch without using any library.
Our main goal is to create an efficient modal which,
- Has a good layout
- Doesn’t break ui when we use overflow in parent component
- Can render content Dynamically
- Clean and Elegant animation
- Looks good (good UI)
- Have more control for User (like clicking outside can close modal) etc.
Let’s get started!
If you prefer video format then you can watch this video
Create your react-app using,
npx create-react-app react-modal
For this tutorial i’m going to use Sass so make sure you have installed node-sass package. To install it do,
npm install node-sass
Let’s create Basic Modal component
open App.js file.
clean unnecessary code.
Now create one button in the App.js file to open and close modal just like this
Exit fullscreen mode
Create one state to open and close modal.
Write below code:
Line 6: Contains modal state which is false initially.
Line 7: A Toggle method to toggle modal state from false to
true and vice-versa.
Line 11: Make sure to connect Toggle() method to onClick of
Next create Modal.js file and Write below code:
Exit fullscreen mode
Now import it in the Modal in App.js file.
Line 17: Here we have imported Modal component. And passed
modal state as show in the props.
Now open Modal.js and write below code
Line 3: Deconstruct Show from the props.
Line 7: We will display modal only when show state is true.
Line 9 to 30: This is the whole Modal layout.
- ModalContainer div contains the modal
- In the modal div, There is one header which contains modal title and close Button (You can use any icon for close button).
- Main tag contains content of the modal.
- Footer has 2 buttons one is submit and another is cancel.
Now when you press a button modal will show and on pressing again it will close the modal.
First Let’s add some styling to our modal.
Create Modal.scss file and import it in the Modal.js file.
Copy and paste this styling in the Modal.scss file.
This will give your modal a better look.
Line 21: By applying this backdrop-filter you can make it
look like frost-glass.
Let’s add Close event in modal
In the App.js file pass toggle method as a props in the modal just like this
Exit fullscreen mode
open Modal.js file and deconstruct close from the props.
Line 3: Deconstruct Close from the props.
We have added close method in 3 places:
Line 16: At the close button.
Line 22: At the cancel button.
Line 11: We have also added close method here too. Why? because whenever user clicks outside it should close the modal. So here, when user clicks on the modalContainer it closes the modal.
Line 13: here we have to stop this click events in the modal else it will close it so for that we have used e.stopPropagation().
hint: You can also add event Listener and add functionality
in which when user clicks esc key, It closes the
modal. (It is good for user experience)
Let’s use Portals to render Modal component
- Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
- Sometimes when we use overflow or z-index properties in the parent component then we need child component (like modal or dialogues) to break container visually, and portals can be very handy to do that because it renders children outside of DOM hierarchy.
ReactDOM.createPortal
(
element,
DOM node where you want to render this element
)
So let’s implement portals in our Modal component.
To use portal we have to create one more element in the dom.
Generally our whole App renders in the div with the id root.
Open index.html file.
and above the root div create one more div with the id modal.
Just like this
Exit fullscreen mode
Open Modal.js file and edit it just like this,
Line 1: Import ReactDom.
Line 6: After return create portal using ReactDom.createPortal , As it’s first argument we have passed whole modal component and for the second argument we have passed the dom node where we want to render it.
Line 34: We want to render our component in the div with id modal.
Let’s make Modal content Dynamic:
open App.js file and pass title as a props and content inside the component as shown below,
Exit fullscreen mode
Here we have passed title as props and modal content as the children.
Open Modal.js and write,
(Final Modal.js code)
Line 5: Deconstruct title and children from the props.
Line 17: Insert title in the curly braces.
Line 22: Render children using the curly braces.
Now if you want to add a little animation in the modal you can watch the video or you can go to the git repository and read code.
React Modal tutorial using hooks
In this tutorial, we are going to learn about how to create a modal in react using hooks.
First, we are going a set up a new react app by using the below command.
Now change your current working directory by using the following commands.
Modal state initialization
Now open the react-modal folder in your favorite code editor and navigate to App.js file and replace with below code.
In the above code, we first imported useState hook from react package and initialized with a value false .
The useState hook returns an array with two properties which are show and setShow . setShow is a function which is used to update the state.
The closeModal and openModal functions are used to opening and closing the modal.
We also added !show in front of button element so that button only renders when a modal is not open.
Creating Modal component
We have initialized our Modal state and functions in the above section, now we are going to create a modal component.
create a new file called Modal.js in your src folder and add the below code.
In the above code, the Modal component is accepting two props(show,closeModal) and we have added a ternary condition to div element.
It means we are adding a modal class to div element if only show prop is true otherwise we are adding hide class.
Using Modal Component
Let’s use the Modal component now by importing it inside App.js file.
Adding CSS classes
Inside your style.css file add the below styles.
Let’s test our modal now by navigating to localhost:3000 .
If you click on show modal button you will see a modal open with a close button like in the below image.
One thing is missing in your modal which is overlay , open your Modal.js file and update with below code.
Here we added a div element with overlay class and onClick handler so that we can also close our modal by clicking on overlay .
Let’s test our Modal again.
React Portals help us to render a component outside the normal dom flow instead of rendering next to the parent component.
Where is child is a react element and container is a dom element we need to render the child.
By using Portals we can solve the styling issues because parent elements styles are applied to the child elements in css, whenever we are creating modals or tooltips we need to render outside from the parent element so that parent styles are not applied to the child.