How to create a simple ‘Hello React’ app
Say “Hello” to improve your understanding of React basics.
In the course of learning React, I have come across a ton of articles and tutorials that have been helpful. Unfortunately, most of these material make a lot of assumption on level of understanding and skip some steps.
My introduction aims to simplify React by showing and explaining in detail, how to create and render a simple component.
For a quicker example, check Facebook’s official docs on React.
Creating in React
There are three steps in creating a project in React,
- Create an element,
- Create a component, and
- Render it.
We will be using CodePen so we don’t have to bother with setup — that part can come in later projects.
Save & Close after you have made the changes above.
Create An Element
On the HTML section of your pen, create a
div element with an id of
app. This is where our JSX code will eventually be rendered.
Now that we have created the element, let’s create the component which will be rendered(displayed) in the element.
Components are the core feature of the React library. They are reusable UI pieces that allow you to separate your code. These different pieces can then be made to interact in interesting ways.
We will create our
Text component by adding the code below to the JS(Babel) section of the pen.
Another way to define a component is to use the ES6 class declaration method. But it is not advised for components like this that have no changing parts.
Now that we have created our component, let’s render it on the browser.
Render (the) Component
This final step displays the created component on a HTML element. As such, this step has two arguments — the component, and the element.
This is what the syntax looks like,
<Component />, document.getElementById(element)
In our example, our component is
Text and our element id is
app. Place the following code below our component code.
At this point, a plain “Hello React” will render on the screen preview.
Here is the complete JSX.
- There is usually only one HTML element where the app is rendered. In our example, we gave it the id
app. This is called the root node and it is where the whole DOM is rendered.
ReactDOM.render()accepts only one root for each of its arguments. If you have two components to pass into the first argument of
ReactDOM.render()for example, you should wrap them in a single
- Always start component names with a capital letter.
- If you are just starting out with React, you should learn props next.
Thank you for reading! If this was helpful, click 💚 so I can know to continue sharing.