React Best Practices

Using React Children for composition

Using React Children for composition

React provides a special prop that you can use to denote content between the start and ending tags.

This is usually seen in HTML elements as:

1<p>Children of p</p>
2
3<div>
4  <p>This is children content of div and p tags</p>
5</div>

In React, you can achieve the same using props.children:

1<Button>
2  <i>icon</i>
3  <span>Content</span>
4</Button>

Inside Button component, you can access children as:

1function Button({ children }) {
2  return <button>{children}</button>
3}

Note that children as a prop does not need to be passed explicitly. React passes whatever content you have passed inside special children prop. Children is fit for passing in large values which can be substituted with any React element, React also provides a dedicated API for dealing with children.

Advantages

1const currentUser = {};
2
3return (
4  <Permissions>
5    <Navbar>
6      <Left />
7      <Right>
8        <Profile>
9          {/* By using children prop we have avoided passing currentUser to components in multiple levels */}
10          <img src={currentUser.image} alt="">
11        </Profile>
12      </Right>
13    </Navbar>
14  </Permissions>
15)
  • Children opens up more patterns like Compound Components.

Compound Components

  1. Too many props, you end up with a 100 props and more that are appended daily.
  2. When you have a component that deals with multiple HTML elements, how do you differentiate what a prop is for: Case in point: isHovered: What is being hovered here? When should someone use this?
  3. Easier stacking order, looks like HTML
1<Accordion onClose={}>
2   <Accordion.Header showCloseButton>Heading</Accordion.Header>
3   <Accordion.Body size="">Body</Accordion.Body>
4</Accordion>

References