Creating A Pop Up Modal In React

Brian Smith
3 min readOct 3, 2021

--

Setting up a modal in React can be tricky depending on the way your components are structured and how those components are used within React. I am going to go through the step of how I set up a pop up modal in React so that you can do the same in your future applications.

My first component interface, component/UserList.js, which you see below is a list of users on the page. I can search to find a specific user or leave the search blank to see all the users. When I scroll my mouse over a users name I can click on that user. This triggers the modal to pop up.

When you click on a user the component interface, component/UserProfile.js, will be activated. This places the UserProfile on top of the UserList. If I did not have a modal set up, the UserProfile component would show up inside of the UserList component. For example, if I clicked on hulk you would see hulk’s entire UserProfile component under the word hulk (see the below image) and the rest of the user names would be listed below the hulk image.

Setting up a modal also involves the use of CSS. Below is the CSS code that I wrote in order to design the structure of the UserProfile component. You will want to make the position: fixed;. This will the modal component in front of the other component. To ensure the alignment of the component is in the proper location, the top and left should both be set to 0. This will place the component at the top left corner of the page. If I were to change the left from 0 to 20px then the modal will be 20px over from the left.

Below is what the component/UserList.js looks like on the backend. I pass through all the attributes for what is needed in the UserProfile component. I set up an on click so that when the end used clicks a user name, that function will be called and will change the state of showUserProfile which will activate the ternary and either show or hide the UserProfile component. In addition, I pass through that function into the UserProfile component.

Now that the ternary is triggered, the UserProfile component shows on the user interface. The below image shows how I set up the structure of the user profile. I also included the Header.js component within the UserProfile component. I passed through that handleClick function as a prop which I called hideUserProfile so that if the user wants to make this component disappear they can click the back button. Once the back button is clicked, the modal is not longer visible to the end user and the UserList component will be displayed.

I hope you learned something new about setting up a modal in React. Happy coding!

--

--