Explain basic code snippet of JSX
Now we are going to create a JSX component inside a react application look at the detailed explanation of the component.
Explanation of JSX Code Snippet: Now we are going to learn the basic properties of JSX code snippets.
- Inserting Multiline HTML Code : While inserting the HTML code in a JSX element , if the HTML code is multi-liner then put the HTML code inside a parenthesis. You can clearly see in the following example that the HTML code inside the ‘jsxElement’ is enclosed with a parenthesis.
- One top level element : If there are multiple elements in the HTML code snippet then they must be wrapped with a parent element. In our example we have wrapped our <h1> and the <p> element with a <div> element.
- Elements must be closed : While writing HTML it is not necessary to close all the tags, at least the system will not throw any error if some tags are not closed. But in case of JSX you cannot leave an element without closing all the tags. It will throw an error .
Creating react application:
Step 1: Create a React application using the following command:
npx create-react-app name_of_the_app
Step 2: After creating the react application move to the directory as per your app name using the following command:
Project Structure: It will look like the following.
Creating the JSX Element: Now we are going to create a JSX Element inside the App component of the App.js file. The steps are discussed below.
- Clear everything inside the App component of the App.js file.
- Create a new variable named ‘jsxElement’ inside the App component.
- Set the value of the ‘jsxElement’ variable to the HTML code snippet you want to display. If the code snippet is multi-liner, make sure that the HTML code snippet is inside a parenthesis.
- Return the ‘jsxElement’ variable from the App component.
- The ‘jsxElement’ variable is an example of a basic JSX element. And the HTML inside the JSX element is the example of a ‘basic code snippet of JSX’.
App.css File: The App.css file is imported at the top. It is the default ‘App.css’ file that comes up with the react project structure. After creating the JSX element we have modified it and added our own stylings inside.
Step to run the application: Open the terminal and type the following command.