Welcome to part-4 of the series. We will learn about JSX first in the series.
We have been creating component in the previous part with JSX and we will again create one more with it.
We are creating a simple functional component Hello, with a div and h1 tag.
After that we will show the component Hello in the App.js file. We are also commenting out the components created in earlier parts.
Now, it will show the component in our http://localhost:3000/
We will now convert the same Hello component to be used without the JSX. React provide us with React.createElement to do that.
So, it takes three parameters — one is the tag which is div in our case, the next is null and the third is the element inside it. For us it is the h1, so we are again using the React.createElement
The second null parameter is the key value pair, which specifies the id or the class attached to the element. I have also added the equivalent code in the commented out JSX code.
id and class
So, with the above the problem with is obvious. Our component have two elements, but most React components have more then 10 elements. So, we have to nest them one inside the other and the code gets complicated soon.
As we have seen the difference with class in JSX. There are some more differences with JSX and we will learn more about them later.
class -> className
for -> htmlFor
Property naming convention are camelCase.
We will learn about the concept of props in React. Till now all our components have been very static and we have not seen the use of component reusability.
Props are passed as attributes to components. In the App.js we are calling the Greetings component three times and each time with a different attribute.
Next, we will move to Greet.js to use the props. First we need to pass the props keyword as parameter. Next, just doing console log to check the value of props. After that in the return statement we are using it by props.name. Notice the curly bracket wrapping it, they are to evaluate the JSX expression.
Now, in our http://localhost:3000/ we can see three different props which were passed from App.js to Greet.js. Also, the console shows the props object.
We have another type of props called children. They are specified within the opening and closing brackets of the component as shown below.
Now, in our Greet.js, we are using it within a paragraph tag as props.children. Also, notice that the h1 and the p tag are wrapped in a pair of empty tag. This is know as React fragment as React needs the same tag as start and end. We could equally use a div tag in it’s place.
It will show as below in localhost.
Next, we will use props within a class component. The passing of attribute from App.js is similar to a functional component.
But in Welcome.js, we will use the props with the this keyword. Also, notice that we have used div instead of a fragment here.
It is showing perfectly in localhost.
This completes part-4 of the series.