February 13, 2022 08:41 am GMT
How
How to use the
Original Link: https://dev.to/fromaline/how-does-react-allow-creating-custom-components-3mbe
How does React allow creating custom components?
React strives to give its users the ability to build encapsulated, reusable components, but how does it implement this logic in JSX?
Here is a simple example of a custom user-defined component, named Greeting
. It renders inside a well-known App
component.
// Greeting.jsxconst Greeting = ({name}) => { return <span>Hi, {name} </span>;}// App.jsxconst App = () => { return ( <div> <Greeting name="Nikita" /> </div> );}
Let's break it down!
How Greeting
works?
Greeting
is just a function, which returns JSX. JSX is syntax sugar for callingReact.createElement
React.createElement
expects three arguments:- type
- props
- children
Let's rewrite our Greeting
component with this new knowledge.
// Greeting.jsxconst Greeting = ({name}) => { return React.createElement( 'span', null, 'Hi, ', name, ' ');}
How to use the Greeting
now?
Turns out, createElement
expects three values as type:
- tag name, like
div
orspan
- a class or a function, that defines custom component
- React fragment type
// App.jsxconst App = () => { return React.createElement( 'div', null, React.createElement(Greeting, {name}) );}
Simply put, createElement
calls the passed function internally and uses its return value to form the component tree.
// Internal intermediate resultconst App = () => { return React.createElement( 'div', null, React.createElement( 'span', null, 'Hi, ', 'Nikita', ' ' ) );}
Verify that it works yourself!
Go to reactjs.org, open the console and paste the last code snippet there.
Then call the App()
and see the end result.
If it's the same as here , you've done a great job!
{ "type": "div", "key": null, "ref": null, "props": { "children": { "type": "span", "key": null, "ref": null, "props": { "children": [ "Hi, ", "Nikita", " " ] }, "_owner": null } }, "_owner": null}
P.S. Follow me on Twitter for more content like this!
Original Link: https://dev.to/fromaline/how-does-react-allow-creating-custom-components-3mbe
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To