Creating a React component from a reference to its class

Tom Szpytman

I generally like to keep callback functions to a minimum. Passing around callback functions gets the job done, but you quickly end up with spaghetti-like code structures that are hard to navigate and debug. I’ve seen a fair number of React developers pass around callback functions to create React components and return Elements, but the use-cases where these would be the best option are few and far between.

A better approach

Let’s take this extremely simple example:

if (hasBook) {
<Bookshelf renderBook={(props) => <Book {…props} />} />
} else {
<Bookshelf renderBook={(props) => <EmptyBook {…props} />} />
}
class Bookshelf {
render () {
return (
<div>
{this.props.renderBook({foo: true, bar: false})}
<div>
);
}
}

My suggestion would be to remove the anonymous functions and re-write them as:

if (hasBook) {
<Bookshelf bookType={Book} />
} else {
<Bookshelf bookType={EmptyBook} />
}
class Bookshelf {
render () {
return (
<div>
{React.createElement(this.props.bookType, {foo: true, bar: false})}
<div>
);
}
}

This, in my opinion, is a much clearer and debuggable solution.

React’s createElement function isn’t new either; it’s actually a function that’s been around since the inception of React, and the function that you’d use to create elements if you weren’t using the JSX syntax.

For those of you using Typescript, you could take the above example a step further by defining your bookType prop as a React.ClassType which takes the props {foo: boolean; bar: boolean;}. The Typescript compiler would then ensure that suitable class references were being passed down to the Bookshelf component.

You shouldn’t need to use React.createElement that often, but for slightly more complicated use-cases such as menus, where menu items are clicked and the page’s content needs to change accordingly, it makes sense to pass around references to the React component classes/functions so that they can be instantiated later.

As always, the take away here is that it’s always worth reading the docs of whichever framework your using. This ensures that your code both harnesses the power of the given framework, and is written in the way that the framework’s engineers intended.

Find more about Tom Szpytman at tomszpytman.com

Tom Szpytman

Written by

Full-stack Software Engineer.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade