createFactory

Advertisement

  • As¬†we¬†know¬†we¬†can¬†create¬†the¬†HTML¬†elements¬†with¬†the¬†help¬†of¬†`createElement()`¬†function.
  • We¬†can¬†avoid¬†**createElement()**¬†and¬†re-use¬†the¬†same¬†type¬†of¬†element¬†with¬†**createFactory()**.

E.g.

import { createElement } from 'react';

const App = () => {
	return (
		createElement(
			'h1',
			{
				'id': 'first',
			},
			'Heading 1'
		)
	)
}

export default App;

It is same as JSX:

const App = () => {
	return (
		<h1 id="first">Heading 1</h1>
    )
}

Suppose we want to create two `<h1>` tags with **createElement()**.

E.g.

createElement(
    'h1',
    {
        'id': 'first',
    },
    'Heading First'
),
createElement(
    'h1',
    {
        'id': 'second',
    },
    'Heading Second'
)

We can use the **createFactory()** function to reuse the `<h1>` tags.

E.g.

let h1 = createFactory( 'h1' );

// ...

h1(
    {
        'id': 'first',
    },
    'Heading First'
),
h1(
    {
        'id': 'second',
    },
    'Heading Second'
)

Here,¬†We¬†have¬†avoided¬†to¬†use¬†**createElement()**¬†function¬†and¬†used¬†**createFactory(¬†‘h1’¬†)**¬†to¬†create¬†same¬†element¬†multiple¬†times.

%d bloggers like this: