Conditional component rendering

One use case for a higher-order component is conditional rendering. For example, depending on the outcome of a predicate, the component is rendered or nothing is rendered. The predicate could be anything that's specific to the application, such as permissions or something like that.

Let's say you have the following component:

import React from 'react';

// The world's simplest component...
export default () => <p>My component...</p>;

Now, to control the display of this component, you can wrap it with another component. Wrapping is handled by the higher-order function.

If you hear the term "wrapper" in the context of React, it's probably referring to a higher-order component. Essentially, this is what it does; it wraps the component that you pass to it.

Now, let's create a higher-order React component:

import React from 'react';

// A minimal higher-order function is all it
// takes to create a component repeater. Here, we're
// returning a function that calls "predicate()".
// If this returns true, then the rendered
// "<Component>" is returned.
export default (Component, predicate) => props =>
predicate() && <Component {...props} />;

The two arguments to this function are Component, which is the component that you're wrapping, and the predicate to call. If the call to predicate() returns true, then <Component> is returned. Otherwise, nothing will be rendered.

Now, let's actually compose a new component using this function, and your component that renders a paragraph of text:

import React from 'react';
import { render } from 'react-dom';

import cond from './cond';
import MyComponent from './MyComponent';

// Two compositions of "MyComponent". The
// "ComposedVisible" version will render
// because the predicate returns true. The
// "ComposedHidden" version doesn't render.
const ComposedVisible = cond(MyComponent, () => true);
const ComposedHidden = cond(MyComponent, () => false);

render(
<section>
<h1>Visible</h1>
<ComposedVisible />
<h2>Hidden</h2>
<ComposedHidden />
</section>,
document.getElementById('root')
);

You've just created two new components using MyComponent, cond(), and a predicate function. Here's the rendered output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.99.7