How does React allow creating custom components?
source link: https://dev.to/fromaline/how-does-react-allow-creating-custom-components-3mbe
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
React Internals (3 Part Series)
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.jsx
const Greeting = ({name}) => {
return <span>Hi, {name} 👋</span>;
}
// App.jsx
const App = () => {
return (
<div>
<Greeting name="Nikita" />
</div>
);
}
Enter fullscreen mode
Exit fullscreen mode
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:- props
- children
Let's rewrite our Greeting
component with this new knowledge.
// Greeting.jsx
const Greeting = ({name}) => {
return React.createElement(
'span',
null,
'Hi, ', name, ' 👋');
}
Enter fullscreen mode
Exit fullscreen mode
👉 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.jsx
const App = () => {
return React.createElement(
'div',
null,
React.createElement(Greeting, {name})
);
}
Enter fullscreen mode
Exit fullscreen mode
Simply put, createElement
calls the passed function internally and uses its return value to form the component tree.
// Internal intermediate result
const App = () => {
return React.createElement(
'div',
null,
React.createElement(
'span',
null,
'Hi, ', 'Nikita', ' 👋'
)
);
}
Enter fullscreen mode
Exit fullscreen mode
👉 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
}
Enter fullscreen mode
Exit fullscreen mode
P.S. Follow me on Twitter for more content like this!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK