Conditionally wrapping components in React
Sometimes, we want to wrap a React component in another component if a certain condition is true
, and not if the condition is false
. One such situation might be when a text is a clickable link if an URL is present, or else just plain text.
One way to implement this requirement could look like that:
|
|
In this example, we only needed to duplicate the <span className="text-classname" />
component, but in more complex situations, the amount of code that would be duplicated can be forbiddingly huge. We want a more generic solution for this issue, some kind of Wrap
component that would allow rewriting the code from above as follows:
|
|
So let’s do it! Here is how I implemented the Wrap
component:
|
|
The lesser-known isValidElement and cloneElement functions from the React API have been declared as Legacy since the release of React 18, which means they are not recommended for use in newly written code. However, as of today, they are not marked for removal in a future major version of React.