9 Ways in React to Manipulate and Work With Components in 2020

Christopher T.

April 1st, 2020

Share This Post

It is a great time to be a web developer as innovations continue to erupt rapidly especially in the JavaScript community! React is an incredible library to build complex user interfaces and if you're new to React then this article might help you understand how powerful it is for web developers to use them at your disposal. And if you're not new to react, then you'll probably not find anything new in this post but hopefully you might something new in this post as I try to expose both old and new strategies to work with react components.

In this article we will be going over 9 ways to manipulate and work with React components in 2020.

Without further ado, let's begin!

1. Component prop

One of multiple ways to have existing components re-use their logic and pass it somewhere else is to provide a way to pass the logic into a custom component by props.

Popular react component libraries like Material-UI use this strategy very often in just about every component they provide.

There are good reasons as to why this is a good way to re-use logic.

If you want an example, have a look at this PrivateRoute component from a Gatsby app. It's a simple component that encapsulates authentication logic. If the current user is not authenticated it will redirect them to the login screen. Otherwise, it will proceed to render a component received from props.component. Since it renders anything it was passed from props.component, it leaves it open to re-use that authentication logic for as many components as you'd like. It makes it a simple but powerful approach to work with routing logic.

P.S: You can also pass a string representing an HTML DOM element like "div" or "span" and it will still render as a component, because react internally calls React.createElement passing it as the element type.

2. Rendering elements, class components or function components in one call

When describing what your user interface should look like, the React dev team recommends to use JSX.

But don't forget that using JSX is ultimately just syntactic sugar for calling React.createElement. So, it's worth mentioning that you can safely use React.createElement to create your components as well!

There are some benefits to using React.createElement over JSX.

One of these benefits that intrigues me the most is that it brings me back to writing regular JavaScript since we're going back to using just functions. Other benefits include avoiding react from handling this call and getting access to all the implementation details in one block of code, so we avoid that extra step that JavaScript has to perform.

The team behind react-final-form makes extensive use of this pattern as a factory to create their field components.

3. Hijack props with Higher Order Components (HOC)

Higher order components had its fair share of glory back in the days as an advanced technique in React for reusing component logic. It still is however. They're basically functions that take a react component as an argument and returns an entirely new component.

Using this approach allows you to overwrite and hijack a component's props inside an "invisible" middle layer. This "middle layer" is where the higher order component's logic is happening. They can choose to overwrite the wrapped component's props or control their rendering behavior.

To demonstrate this I have written a barebones withAuthValidation higher order component that is going to be passed an input (DeactivatorInput) that is to be made available only to admin users. It first takes a component as props, performs some authentication logic and if the user is not authenticated then it will attempt to disable the input:

import React from 'react'

function isAuthed(token) {
  // some auth logic
}

const withAuthValidation = (WrappedComponent) => {
  return (props) => {
    if (isAuthed(props.token)) {
      return <WrappedComponent {...props} />
    }
    return <WrappedComponent {...props} disabled />
  }
}

const DeactivatorInput = ({ style, ...rest }) => (
  <input
    {...rest}
    style={{
      minWidth: 200,
      border: '1px solid rgba(0, 0, 0, 0.5)',
      borderRadius: 4,
      padding: '6px 12px',
      ...style,
    }}
    placeholder="Search a user to deactivate"
  />
)

// Applies the higher order component. This is the component we use to render
//    in place of DeactivatorInput
const DeactivatorInputWithAuthValidation = withAuthValidation(DeactivatorInput)

function App() {
  return (
    <div>
      <DeactivatorInputWithAuthValidation />
    </div>
  )
}

export default App

higher-order-component-in-react

4. Reuse component logic with Render Props

I still remember when render props were first being brought to the surface, it quickly trended across the React community and became a widely adopted pattern to reuse code logic with components.

Using this pattern solves the same probems that higher order components try to solve. But plenty of developers favor using the render prop pattern for one very good reason: Higher order components introduced a problem where you needed to copy over static methods.

Another good reason why render props were heavily favored by many is that you don't really instantiate a new component instance as you would with higher order components. You only need to use a single component to implement the pattern (which gives a more "native" feel to react):

function AuthValidator({ token, render, ...rest }) {
  if (isAuthed(token)) {
    return render({ authenticated: true })
  }
  return render({ authenticated: false })
}

const DeactivatorInput = ({ style, ...rest }) => (
  <input
    {...rest}
    style={{
      minWidth: 200,
      border: '1px solid rgba(0, 0, 0, 0.5)',
      borderRadius: 4,
      padding: '6px 12px',
      ...style,
    }}
    placeholder="Search a user to deactivate"
  />
)

function App() {
  return (
    <div>
      <AuthValidator
        token="abc123"
        render={({ authenticated }) => (
          <DeactivatorInput disabled={!authenticated} />
        )}
      />
    </div>
  )
}

5. Reuse component logic with children as functions

This is basically the same as using the render prop approach, it just looks different because react already puts children in between the opening component tag and the closing tag, so logically it will stay there:

function AuthValidator({ token, children, ...rest }) {
  if (isAuthed(token)) {
    return children({ authenticated: true })
  }
  return children({ authenticated: false })
}

const DeactivatorInput = ({ style, ...rest }) => (
  <input
    {...rest}
    style={{
      minWidth: 200,
      border: '1px solid rgba(0, 0, 0, 0.5)',
      borderRadius: 4,
      padding: '6px 12px',
      ...style,
    }}
    placeholder="Search a user to deactivate"
  />
)

function App() {
  return (
    <div>
      <AuthValidator token="abc123">
        {({ authenticated }) => <DeactivatorInput disabled={!authenticated} />}
      </AuthValidator>
    </div>
  )
}

6. Reuse component logic with multiple renderer functions

You're not limited to one render/children function, you can have multiple:

import React from 'react'
import Topbar from './Topbar'
import Sidebar from './Sidebar'
import About from './About'
import Contact from './Contact'
import PrivacyPolicy from './PrivacyPolicy'
import Dashboard from './Dashboard'
import { Router } from '@reach/router'

function App() {
  return (
    <Router>
      <Dashboard
        topbar={({ authenticated }) => (
          <Router>
            <Topbar path="*" authenticated={authenticated} />
          </Router>
        )}
        sidebar={() => (
          <Router>
            <Sidebar path="*" />
          </Router>
        )}
        view={({ authenticated }) => (
          <Router>
            <About path="/about" />
            <Contact path="/contact" />
            <PrivacyPolicy path="/privacy-policy" />
            <Admin path="/admin" authenticated={authenticated} />
          </Router>
        )}
      />
    </Router>
  )
}

export default App

However I don't really like nor recommend this approach because it can be very limiting when writing the render method of Dashboard. But it can be useful in a situation like above, where the sidebar or topbar won't be moving anywhere else in the UI.

7. Reuse component logic with React Hooks

Then came react hooks, which had taken the community by storm to this day.

Hooks allow you to solve any of the problems listed above and brings you back to normal JavaScript by working with what it feels to be just functions:

import React from 'react'

function useStuff() {
  const [data, setData] = React.useState({})

  React.useEffect(() => {
    fetch('https://someapi.com/api/users/')
      .then((response) => setData(response.json()))
      .catch((err) => setData(err))
  }, [])

  return { data, setData }
}

function App() {
  const { data } = useStuff()

  if (data instanceof Error) {
    return <p style={{ color: 'red' }}>Error: {data.message}</p>
  }

  return <div>{JSON.stringify(data, null, 2)}</div>
}

One problem that render props introduced was that when we render multiples of render prop components nested under another, we encounter a "callback hell" looking something like this:

import React from 'react'
import ControlPanel from './ControlPanel'
import ControlButton from './ControlButton'

function AuthValidator({ token, render, ...rest }) {
  if (isAuthed(token)) {
    return render({ authenticated: true })
  }
  return render({ authenticated: false })
}

function App() {
  return (
    <div>
      <AuthValidator
        render={({ authenticated }) => {
          if (!authenticated) {
            return null
          }
          return (
            <ControlPanel
              authenticated={authenticated}
              render={({ Container, controls }) => (
                <Container
                  render={({ width, height }) => (
                    <div style={{ width, height }}>
                      {controls.map((options) =>
                        options.render ? (
                          <ControlButton
                            render={({ Component }) => (
                              <Component {...options} />
                            )}
                          />
                        ) : (
                          <ControlButton {...options} />
                        ),
                      )}
                    </div>
                  )}
                />
              )}
            />
          )
        }}
      />
    </div>
  )
}

When working with hooks, it can look something like this:

import React from 'react'
import useControlPanel from './useControlPanel'
import ControlButton from './ControlButton'

function useAuthValidator({ token }) {
  const [authenticated, setAuthenticated] = React.useState(null)

  React.useEffect(() => {
    if (isAuthed(token)) setAuthenticated(true)
    else setAuthenticated(false)
  })

  return { authenticated }
}

function App() {
  const { authenticated } = useAuthValidator('abc123')
  const { Container, width, height, controls } = useControlPanel({
    authenticated,
  })

  return (
    <Container>
      <div style={{ width, height }}>
        {controls.map((options) =>
          options.render ? (
            <ControlButton
              render={({ Component }) => <Component {...options} />}
            />
          ) : (
            <ControlButton {...options} />
          ),
        )}
      </div>
    </Container>
  )
}

8. Reuse component logic by working with children

I still sometimes find people question how a component would receive certain props when not explicitly passed like this:

const DeactivatorInput = ({
  component: Component = 'input',
  style,
  opened,
  open: openModal,
  close: closeModal,
  ...rest
}) => (
  <div>
    <Component
      type="email"
      onKeyPress={(e) => {
        const pressedEnter = e.charCode === 13
        if (pressedEnter) {
          openModal()
        }
      }}
      style={{
        minWidth: 200,
        border: '1px solid rgba(0, 0, 0, 0.5)',
        borderRadius: 4,
        padding: '6px 12px',
        ...style,
      }}
      placeholder="Search a user to deactivate"
      {...rest}
    />
    <Modal isOpen={opened}>
      <h1>Modal is opened</h1>
      <hr />
      <button type="button" onClick={closeModal}>
        Close
      </button>
    </Modal>
  </div>
)

function App() {
  return (
    <ControlPanel>
      <DeactivatorInput />
    </ControlPanel>
  )
}

Understandly one question the validity of this code since we don't see any props being passed to DeactivatorInput, but there's actually a way.

It's nice to have the ability to inject additional props as needed to react elements and not just to components. React.cloneElement is capable of doing just that for you:

function ControlPanel({ children, ...rest }) {
  const [opened, setOpened] = React.useState(false)
  const open = () => setOpened(true)
  const close = () => setOpened(false)
  return (
    <div>{React.cloneElement(children, { opened, open, close, ...rest })}</div>
  )
}

React also provides a couple of other utilities when working with children, like React.Children.toArray in which you can use in conjunction with React.cloneElement for multiple children:

function ControlPanel({ children, ...rest }) {
  const [opened, setOpened] = React.useState(false)
  const open = () => setOpened(true)
  const close = () => setOpened(false)
  const child = React.Children.toArray(children).map((child) =>
    React.cloneElement(child, { opened, open, close, ...rest }),
  )
  return <div>{child}</div>
}

This strategy was commonly used when implementing compound components--however, a better way to approach this similar functionality now is by using react context because the drawbacks of the former solution was that only direct children can receive the props passed to React.cloneElement unless a recursion was performed in each nested children which isn't necessary. With react context you can place children anywhere no matter how nested they are and they will still be able to be synchronized on your behalf.

Rumble charts is a successful example in which it heavily uses React.Children.map to decide its children's behavior.

9. Dynamically creating deeply nested components

In this section we will go over recursion and how it helps simplify the process of working with react components.

Lets say we had a component that have repeating elements, like a navbar containing a menu button as a dropdown for example. A dropdown can have multiple items and each item can have its own nested dropdown like so:

react dropdown menu with nested menus recursion

We don't want to have to do manual labor and code these nested menus ourselves. The only manual labor we should perform is writing the recursion:

import React from 'react'
import Button from '@material-ui/core/Button'
import Menu from '@material-ui/core/Menu'
import MenuItem from '@material-ui/core/MenuItem'
import './styles.css'

const items = [
  { to: '/home', label: 'Home' },
  { to: '/blog', label: 'Blog' },
  { to: '/about', label: 'About' },
  { to: '/contact', label: 'Contact' },
  {
    to: '/help-center',
    label: 'Help Center',
    items: [
      { to: '/privacy-policy', label: 'Privacy Policy' },
      { to: '/tos', label: 'Terms of Service' },
      { to: '/partners', label: 'Partners' },
      {
        to: '/faq',
        label: 'FAQ',
        items: [
          { to: '/faq/newsletter', label: 'Newsletter FAQs' },
          { to: '/faq/career', label: 'Employment/Career FAQs' },
        ],
      },
    ],
  },
]

const MyMenu = React.forwardRef(
  ({ items, anchorEl: anchorElProp, createOnClick, onClose }, ref) => {
    const [anchorEl, setAnchorEl] = React.useState(null)
    return (
      <Menu
        ref={ref}
        open={Boolean(anchorElProp)}
        onClose={onClose}
        anchorEl={anchorElProp}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        {items.map((item) => (
          <div key={item.to}>
            <MenuItem onMouseEnter={item.items && createOnClick(setAnchorEl)}>
              {item.label}
            </MenuItem>
            {item.items && (
              <MyMenu
                key={item.to}
                items={item.items}
                anchorEl={anchorEl}
                createOnClick={createOnClick}
                onClose={() => setAnchorEl(null)}
              />
            )}
          </div>
        ))}
      </Menu>
    )
  },
)

function App() {
  const [anchorEl, setAnchorEl] = React.useState(null)
  const createOnClick = (callback) => {
    return (e) => {
      e.persist()
      return callback(e.currentTarget)
    }
  }

  return (
    <div>
      <Button onMouseEnter={createOnClick(setAnchorEl)} variant="outlined">
        View More
      </Button>
      <MyMenu
        items={items}
        anchorEl={anchorEl}
        createOnClick={createOnClick}
        onClose={() => setAnchorEl(null)}
      />
    </div>
  )
}

Creating components like these is a good way to make your components reusable and dynamic.


Tags

javascript
react
typescript
recursion
compound components
render prop
higher order component
react hooks
rumble charts
react cloneelement
react createelement

Subscribe to the Newsletter
Get continuous updates
© jsmanifest 2021