Saturday, July 31, 2021

Intro to React Applications, JSX & Insights

 So I found that I was not as thoroughly aware of how JSX works so this post is a placeholder for any insights I may gather about JSX.

Hello World JSX

Following is how you would create a react application:

npx create-react-app jsx_learning_repo

Once you have a folder / directory called jsx_learning_repo created, you may go into it and look for the file index.js to modify.
It is likely to be located in a location similar to this one : https://github.com/mrarthurwhite/jsx_learning_repo/tree/master/src

Now that you have an application created you may write the following hello world react application. In Index.js write your greeting:

[BEGIN CODE] [END CODE]

React DOM in lines 2 and 7 is a renderer for React: it handles rendering components to the DOM or to a string for server-side rendering.
Line 9 obtains the root element in your index.html file which is your single page application. It is in this div element with id of root that all of your react components will render.
Once you have edited the index.js file you may view it by running your application. You run it by going to the folder/directory jsx_learning_repo for the application and typing:

npm start

Hello World JSX part 2

In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces ( again this is the edited version of index.js):

[BEGIN CODE] [END CODE]

The above illustrates the use of JSX and interpolating curly brackets "{}" to insert variable assignments into expressions. 

You can put any valid JavaScript expression inside the curly braces in JSX.
For example,
2 + 2,
or
user.firstName,
or
formatName(user)
are all valid JavaScript expressions. Here is an illustration of expressions:

[BEGIN CODE]

[END CODE]

The above gives the following output :

 

 

Hello World JSX with user defined components

Previously, we noticed that we could use html elements or DOM tags like <h3> & <div>
However, elements can also represent user-defined components like: <Hi>.

When React sees an element representing a user-defined component, it passes JSX attributes and children to this component as a single object.
We call this object “props”.

For example:

[CODE] [/CODE]

In the above the functional component "hi" is the function Hi above in line 4 with its argument called props. In line 8 we define this user defined component Hi. And finally in line 11 we use this  component or render it to the DOM.

No comments:

Total Pageviews

Popular Posts