9 Ways in React to Manipulate and Work With Components in 2020
Tags: react, javascript, node, webdev
Published: 2020-04-05 17:19:09

Find me on [medium](https://medium.com/@jsmanifest)

It is a great time to be a web developer as innovations continue to erupt rapidly especially in the JavaScript community! [React](https://reactjs.org/) 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](https://github.com/mui-org/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](https://github.com/gatsbyjs/gatsby/blob/master/examples/simple-auth/src/components/PrivateRoute.js) component from a [Gatsby](https://www.gatsbyjs.org/) 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](https://github.com/facebook/react/blob/master/packages/react/src/ReactElement.js#L146) 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](https://github.com/final-form/react-final-form/blob/master/src/renderComponent.js) 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:

```jsx
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](https://jsmanifest.s3-us-west-1.amazonaws.com/posts/9-ways-in-react-to-manipulate-and-work-with-components-in-2020/higher-order-component-in-react.jpg)

## 4. Reuse component logic with Render Props

I still remember when [render props were first being brought to the surface](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce), 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](https://reactjs.org/docs/higher-order-components.html#static-methods-must-be-copied-over).

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):

```jsx
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:

```jsx
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:

```jsx
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](https://reactjs.org/docs/hooks-intro.html), 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_:

```jsx
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:

```jsx
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:

```jsx
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:

```jsx
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:

```jsx
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:

```jsx
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](https://www.youtube.com/watch?v=hEGg-3pIHlE)--however, a better way to approach this similar functionality now is by using [react context](https://reactjs.org/docs/context.html) 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](https://github.com/rumble-charts/rumble-charts/blob/master/src/helpers/proxyChildren.js) 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](https://www.geeksforgeeks.org/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](https://jsmanifest.s3-us-west-1.amazonaws.com/posts/6-practices-in-react-you-might-find-effective/react-dropdown-menu-with-nested-menus-recursion.gif)

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:

```jsx
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.

Find me on [medium](https://medium.com/@jsmanifest)