A React Component is a function that returns a React Element.
What's a React Element?
Great question!
A React Element is anything between angle brackets:
<h1>Title</h1>
<div>...content...</div>
<App />
<Pokemon />
These are all React Elements because they're wrapped in JSX angle brackets.
These elements look like HTML tags but aren't.
Those tags get converted to function calls:
React.createElement("h1", null, "Title");
React.createElement("div", null, "...content...");
React.createElement(App);
React.createElement(Pokemon);
So React Elements can be created from host elements like h1
and div
or Components like App
and Pokemon
.
How do I Create a Component?
A React Component is just a function that returns a React Element.
function MyComponent() {
return <h1>Look what we did!</h1>;
}
You can then use it by creating a React Element from it:
function App() {
return (
<div>
<MyComponent />
</div>
)
}
Now you know how to create a component!
Give it a Try!
Give your newfound knowledge a try.
Open this CodeSandbox directly in your browser and extract a component.
Find the <h1>Bulbasaur</h1>
React Element and turn it into a component.
Follow the 🧵 on Twitter:
Subscribe on YouTube:
Top comments (4)
Is CreateElement a huge part of React convention? How is it I’ve never encountered this and how does using it compare to rendering html by using JSX in functional components?
Hi Jen!
Yes. Most React developers never interact with React.createElement directly. But it is a function that every React developer uses indirectly.
JSX is a syntax extension that works in the compilation phase — likely Babel.
It just looks for angle brackets and turns them to React.createElement calls before they get to the browser.
This is the reason that every module with a component needs to
import React from "react"
, even if your code does not directly refer to that import.Here are more details on the Babel plugin that powers this in most React apps: babeljs.io/docs/en/babel-plugin-tr...
I hope this was helpful happy to dive in more.
Michael
Thanks for this! I like the short incremental approach you have to teaching.
There might be an error between the first and second code example though. MyComponent Vs MyPokemon
Nice read!
Thank you! And thanks for catching that error! Fixed 🙌