createFactory
createFactory
lets you create a function that produces React elements of a given type.
const factory = createFactory(type)
Usage
Creating React elements
You shouldn’t use createFactory
in new code. In the existing code, it’s typically used as an alternative to JSX:
import { createFactory } from 'react'; const button = createFactory('button'); export default function App() { return button({ onClick: () => { alert('Clicked!') } }, 'Click me'); }
Since createFactory
has been deprecated, you need to remove it from your project’s code.
For example, you can convert it to use createElement
instead of createFactory
like this:
import { createElement } from 'react'; export default function App() { return createElement('button', { onClick: () => { alert('Clicked!') } }, 'Click me'); };
Alternatively, you can convert it to use JSX:
export default function App() { return ( <button onClick={() => { alert('Clicked!'); }}> Click me </button> ); };
Every pattern that uses createFactory
can be converted to either of the two styles above.
Deep Dive
How is createFactory implemented?
How is createFactory implemented?
The full implementation of createFactory
looks like this:
import { createElement } from 'react';
function createFactory(type) {
return createElement.bind(null, type);
}
If your project uses createFactory
a lot, you may copy this helper into your project or publish it on npm.
Reference
createFactory(type)
Call createFactory(type)
to create a factory function which produces React elements of a given type
.
import { createFactory } from 'react';
const button = createFactory('button');
Then you can use it to create React elements without JSX:
export default function App() {
return button({
onClick: () => {
alert('Clicked!')
}
}, 'Click me');
}
Parameters
type
: Thetype
argument must be a valid React component type. For example, it could be a tag name string (such as'div'
or'span'
), or a React component (a function, a class, or a special component likeFragment
).
Returns
Returns a factory function. That factory function receives a props
object as the first argument, followed by a list of ...children
arguments, and returns a React element with the given type
, props
and children
.