React enhances lesson 2: Render component layout is more flexible with Grid and Slots

Tram Ho

Hello friends!

Today I’m back with the advanced Reactjs series. In the previous post we learned about how to write a React hook that is complete and reusable for your entire project from now on. In this article I will talk about creating a general layout for the component, in order to reuse this component later.

Remember: Component reuse is vital when scaling your app! . Because when your application grows and has thousands of components, the more unrelated the components, the bigger the size of your application, the more troublesome, that every time you look at it you just want to throw computer go! Trust me!

Live demo

Before you read on, see a live demo Here you wait?

Preamble

Suppose we have components with similar layout, as shown below:

The component will be laid out in such areas, but rendering something in it is highly customizable. This layout can be suitable for Modal, also suitable for Alert, Toast, ….. and many other things. So it will be reused a lot in the project. Minimize the need to rewrite the same code over and over again.

Begin

1. Create a Slots Context Provider

Give me 1 slot! Do you find this saying very popular? A slot is an “order” to reserve a place first, then either to pick it up or not to take it.

The same is true of the Slots Provider that we are about to create, it will create a series of slots, then whoever takes the slots to display will enter the area that we have laid out. Here we will create the following slots:

  • header
  • closeIcon
  • divider
  • Nội dung
  • footer
  • buttonGroup

… Corresponding to the partitions of the designed layout in the image above.

So when using it, we would write something like this:

The good thing about using Slots is that you don’t need to care about the order of the slots, just enter the correct slot name. For example, if you change the order in which slots are written as follows, the component will still render the same layout.

OK, come on! Here is the code for SlotsProvider, this is just pure React Context so there is nothing to discuss:

2. Create a SlotWrapper

This is just a Wrapper, in order to wrap anything you want to render to the correct Slot by specifying a slot name for it:

3. Write a test component, showing the designed layout

We just wrap all the children of the component in <SlotProvider... At the same time created slots for it, in each slot, here I have inserted a className for it.

4. Just a little CSS!

That is done Now let’s test!

5. Use

Demo Here

6. Finish

Hope this article is useful to everyone, if there is any place that makes it difficult to understand, please comment below! I am very happy to answer! Thank you for watching my post!

Share the news now

Source : Viblo