Code Explanation and Introducing JSX - Hello World! - part 2


ReactJs - What is JSX? & index.js


Welcome to my react series. I'll introduce you to JSX and walk you through the code.

The first file that runs in your browser when you launch the server, open a React application, or type localhost:3000 into the address bar is index.js.  

React Entry Point - index.js Overview

When we open the index.js file, we can see that ReactDom has been imported from the react-dom/client package, which offers DOM-specific methods for rendering react elements into the DOM.

React Tutorial: an overview index.js


Here, "import" refers to module, which is next generation JavaScript code. You learned about it in plain JavaScript, but let me expand on it a little to help you get more comfortable with it. 

We can divide our application into multiple files using modules. A module is simply a file that, depending on the situation, may include classes or functions. With the "export" and "import" directives, we may interchange functionality.

import: It enables the use of functionality imported from another file. so that we can import the function, class, or variables and use them in the file from which we are importing them

export: Exporting a variable, method, or class makes it externally accessible.

The other line we are importing, CSS file and the component we will learn more about them in detail later for now lets talk about this './'  before css and App file.

import './index.css';
import App from './App';

When we import the file from the same directory we need to use dot followed by slash then file name must be enclosed in a single or double quote.

ReactDOM.createRoot()

This is root API. ReactDOM object is being imported from the react-dom package, and createRoot() method is being called on it. The DOM is essentially handled and updated by ReactDOM. To render the react application we pass the DOM element to ReactDOM.createRoot() and then it passed react element which is APP component, to the render() method, which typically renders our primary react component onto the root element.

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

We don't need to touch the file at all when we're just getting started. Your code will be written in the App.js file, which contains all of the nested components that represent your entire application.

What is JSX?

When you open your App.js file, HTML is included, which is something that is not typically seen in vanilla JavaScript. We defined it as JSX, it allows to insert HTML code into JavaScript file.

When selecting an element or creating an element in vanilla JS, we must use the getElementById() or querySelector() methods, however in React, we don't need to provide step-by-step instructions. React uses the Babel compiler to convert JSX code into easy-to-understand JavaScript objects. These objects are used by React to create and maintain the DOM.

Additionally, React DOM escapes any values embedded in JSX before rendering them, preventing injection threats. Therefore, it is okay to use user input in JSX.

React Without JSX

Let's first look at how the internals of JSX function work before moving on. Look at React.createElement first. React.createElement is another alternate method that we can use. According to the official react documentation 

Each JSX element is simply syntactic sugar for calling React.createElement()

It requires three arguments.

React.createElement(component, {props}, ...children)

  • The first argument is component or element. If it's a html element, you can pass it as a string, such as 'div' or'span,' but if it's a component, you don't need to wrap it in string.
  • The second argument is object or props, which sets all of the element's attributes, such as className. If there are no attributes, you can pass an empty object {} or null after the comma.
  • The third argument can be text that appears between the opening and closing div tags, or it can be a child element. We can pass child element as a third argument for that we would call React.createElement again. You can skip the third argument if there is no content or child element..


return ( 
	<h1 className="element">Hello World!</h1>
)

The syntax below can be used to build a react element, which will output "Hello World!" on the screen and function similarly to the JSX example above.

return (
  React.createElement(
   'h1',
   {className: 'element'},
   'Hello, World!'
);
)

JavaScript Expressions in JSX 

Now we know we can insert HTML code into JavaScript file, but we can also include JavaScript expressions in JSX by enclosing them in curly braces. 

These curly brackets allow you to perform any valid JavaScript expression and output the dynamic value on the screen.

const App = () => {
  const name = 'React';
  return (
    <div className="App">
      <h1>welcome {name}</h1>
    </div>
  );
}

Similarly, by passing the function inside curly brackets, we may call the function—which is also a JavaScript valid expression—and embed the result in the <p> element.

function App() {
  function number(num1, num2) {
	return num1 * num2;
  }
  return (
    <div className="App">
      <h1>Hello React</h1>
      <p>{number(6, 2)}</p>
    </div>
  );
}

Note - Don't add quotes around curly braces, only for string values. 

When adding HTML properties, use the camelCase convention, for example, class becomes 'className'. If your code contains an empty tag, such as img, input, or hr, close it with />.

ex-
<img src="" />

The primary thing to remember is that a script or file can only have one root element or parent element, and all children elements can be contained inside of the parent element, or else a rendering error would occur.

ex-
<div>
  <h1>Hello world!</h1>
  <p>It is beautifyl</p>
</div>

Also, I want to point you that you can use the shorter syntax "<></>," an empty tag, if you don't want to enclose your child element within the div or another element in some circumstances. Please be aware that neither keys nor attributes are supported.

ex-


<>
  <h1>Hello world!</h1>
  <p>It is beautifyl</p>
<>

Or, we could apply React.Fragment, It allowed you to group a list of children without the use of a wrapper and it might include keys; we'll look at how to add keys later.

<React.Fragment>
  <h1>React</h1>
  <p>React is a javascript library</p>
</React.Fragment>

Comments in React and JSX

Let's see how we can add comments in React. 

why we make use of comments, we use comments to describe how the code works and alternative solutions that we do not want to execute. Make sure not to use it for summaries, explanations, or anything like; your code should already be simple to understand. Comment in react components can be single-line or multiline, just like in regular JavaScript.

Single line
 // I am single line comment 
Multiline
 /* 
  multi
  line 
  comment
 */


In JSX, we enclose it in curly braces and utilise a multi-line style comment. If you are using Visual Studio Code, you can also utilise Shotcut by selecting a line of code and pressing Ctrl + / on a Windows or Command + / on a Mac to comment and uncomment it.


{/* A JSX single line Comment */}

{/* 
  A JSX multi-line comment
  It should be inside the braces
*/}

Conclusion

I described the index.js file, the modules which is the new language of JavaScript code, and how react inserts code into the root element. This post will explain JSX and its inner workings, as well as how to add comments to both React and JSX.





0 Comments:

Post a Comment