Learning Intro to React | JSX | Components

Learning Intro to React | JSX | Components

1 Like

What is Pure React Code ?

Writing React code without using any additional state management libraries like Redux or MobX. Instead, it relies solely on React’s built-in state management system, component lifecycle methods, and using hooks like useState and useEffect.

1 Like

A React component is considered pure it renders the same output for the same state and props.For this type of class component, React provides the PureComponent base class. Class components that extend the React. PureComponent class are treated as pure components

1 Like

To understand pure component in React we have to learn about pure functions. Pure functions are a programming concept, any function is said to be pure if it meets the following conditions. The components that do not re-render when the value of props and state has been updated with the same values.
In the React component is considered pure renders the same output for the same state and props. This type of class component, React provides the Pure Component base class.

1 Like

What is JSX and Component ?

ReactJS has provided us a Pure Component. If we extend a class with Pure Component, there is no need for shouldComponentUpdate() Lifecycle Method. ReactJS Pure Component Class compares current state and props with new props and states to decide whether the React component should re-render itself or Not.
In simple words, If the previous value of state or props and the new value of state or props is the same, the component will not re-render itself. Since Pure Components restricts the re-rendering when there is no use of re-rendering of the component. Pure Components are Class Components which extends React.PureComponent.

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML.

Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components.

JSX is an extension to the JavaScript language syntax which provides a way to structure component rendering using syntax familiar to many developers commonly used in React

Writing “pure” React code generally means using the core features of React without relying heavily on external libraries or advanced React features like hooks.
“pure” React code can be a subjective concept, and it’s essential to balance the desire for simplicity with the practical needs of your application. Using some well-maintained third-party libraries can often save development time and improve code quality when they address specific concerns effectively. Strive for code that is maintainable, scalable, and readable while leveraging the power of React’s ecosystem.

For writing pure react code we use two cdn link in head of html:
1-: React
2-: ReactDom
react is used for creating element and reactdom is used for rendering the element on the server
Syntax:
let div = React.createElement(‘div’, null, Hello World);
const root = ReactDOM.createRoot(document.getElementById(‘root’));
root.render(div);

writing pure react is real pain it means this is very difficult task for writing big project code that’s why we use third-part environment that is JSX(JavaScript Xml) it’s provide to easyness in writing react code in compare of pure react code.

1 Like

JSX:
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code directly within JavaScript. It is commonly used with React to describe the structure of user interfaces. JSX code looks similar to HTML but is actually a syntactic sugar that gets transformed into regular JavaScript function calls.

With JSX, you can write React components more intuitively and concisely, making it easier to understand the structure of your UI.
JSX is just a more readable and expressive way of writing React component structures, making it widely used in the React ecosystem.

React Components:
React components are the building blocks of user interfaces in React applications. They are reusable, self-contained units of code that define how a part of the user interface should be rendered based on the input data (props) they receive. Components allow you to break down your user interface into smaller, manageable pieces, making it easier to maintain, test, and reason about the code.

There are two types of React components:
1-:Functional Components:
Functional components are JavaScript functions that receive props as their arguments and return the JSX (or elements) that should be rendered.
2-:Class Components: Class components are ES6 classes that extend React.Component.

In both cases, you can use these components in other parts of your application or compose them to create more complex user interfaces.

1 Like

Pure React code:
React is a Javascript library for building user interfaces. React is not a framework.
React core only includes the APIs necessary to define components. It does not include the reconciliation algorithm or any platform-specific code. It is used both by React DOM and React Native components.

 const header=React.createElement("h1",{id:"head"},"Hello Mohan...")
        const img=React.createElement("img",{src :'https://tse4.mm.bing.net/th?id=OIP.4LTT4JjJ1JVceRNUc235MQHaE8&pid=Api&P=0&h=180'})
        const button=React.createElement("button",{},"click here")
        const div =React.createElement("div",{},[header,img,button])
        const root=ReactDOM.createRoot(document.getElementById("root"));
        root.render(div)
1 Like

JSX:

  • JSX, which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications — like Vue apps, for instance.
    Components:
    Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML.
    Components come in two types, Class components and Function components:
    The component’s name MUST start with an upper case letter.
    Class components:
    A class component must include the extends React.Component statement. This statement creates an inheritance to React.Component, and gives your component access to React.Component’s functions.
    Function components:
    A Function component also returns HTML, and behaves much the same way as a Class component, but Function components can be written using much less code.
1 Like
<body>
  <div id="root">not rendered</div>
  <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
  <script>
    // Your code is going to go here
  </script>
</body>

Question:- `What is Pure React Code ?`
Answer:-  Now open above file in your browser. On Mac, hit ⌘ (command) + O in your favorite browser, and on Windows and Linux hit CTRL + O to open the Open prompt. Navigate to wherever you saved the file and open it. You should see a line of text saying "not rendered".

-> We're adding a root div. We'll render our React app here in a sec. It doesn't have to be called root, just a common practice.

-> We have two script tags.
    (1) The first is the React library. This library is the interface of how to interact with React; all the methods (except one) will be via this library. It contains no way of rendering itself though; it's just the API.
    (2) The second library is the rendering layer. Since we're rendering to the browser, we're using React DOM. There are other React libraries like React Native, React 360 (formerly React VR), A-Frame React, React Blessed, and others. You need both script tags. The order is not important.

-> The last script tag is where we're going to put our code. You don't typically do this but I wanted to start as simple as possible. This script tag must come after the other two.

-> In the last script tag, put the following. Here 'App' is Functional Component Name startwith Capital Letter. This is about the simplest React app you can build.

// Your piece of code [React Component]
const App = () => {
  return React.createElement(
    "div",
    {},
    React.createElement("h1", {}, "Adopt Me!")
  );
};

ReactDOM.render(React.createElement(App), document.getElementById("root"));

-> The first thing we do is make our own component, App. React is all about making components. And then taking those components and making more components out of those.

-> There are two types of components, Function components and Class components. This is a function component. We'll see class components shortly.

-> A function component must return markup (which is what React.createElement generates.)

-> These component render functions have to be fast. This function is going to be called a lot. It's a hot code path.

-> Inside of the render function, you cannot modify any sort of state. Put in functional terms, this function must be pure. You don't know how or when the function will be called so it can't modify any ambient state.

-> React.createElement creates one instance of some component. If you pass it a string, it will create a DOM tag with that as the string. We used h1 and div, those tags are output to the DOM. If we put x-custom-date-picker, it'll output that (so web components are possible too.)

-> The second empty object {} (you can put null too) is attributes we're passing to the tag or component. Whatever we put in this will be output to the element (like id or style.)

-> First we're using document.getElementById to grab an existing div out of the HTML document. Then we take that element (which we called container) and pass that into ReactDOM.render. This is how we signal to React where we want it to render our app. Note later we can call ReactDOM.render again to change what the root of our React app looks like (I rarely need to do that.)

-> Notice we're using React.createElement with App as a parameter to ReactDOM.render. We need an instance of App to render out. App is a class of components and we need to render one instance of a class. That's what React.createElement does: it makes an instance of a class. An analogy is that App as a class of components is like Honda has a line of cars called Civics. It's a whole line of cars with various different options and parameters. An instance of a Civic would be one individual car. It's a concrete instance of the Civic car line.

Note: ReactDOM.createRoot is a new API as of React v18. The old ReactDOM.render that we're using here is still available (but will be deprecated) in v18, you'll just need to update it to opt into future features in v18 (whenever that gets released.)

1 Like

In simple words, If the previous value of state or props and the new value of state or props is the same, the component will not re-render itself. Since Pure Components restricts the re-rendering when there is no use of re-rendering of the component. Pure Components are Class Components which extends

1 Like
🚩 Everything in React is Components.
Question:- `What is JSX?`
Answer:-  
  -> JSX stands for JavaScript XML. JSX is one of the core concepts of React.
  -> React JSX is a syntax extension of JavaScript. 
  -> It enables developer to create virtual DOM using XML syntax.
  ->  It compiles down to pure JavaScript (React.createElement function calls). 
  -> Since it compiles to JavaScript, it can be used inside any valid JavaScript code.
  -> JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together.

                                const jsx = <h1>This is JSX</h1>

  -> This is simple JSX code in React. But the browser does not understand this JSX because it's not valid JavaScript code. This is because we're assigning an HTML tag to a variable that is not a string but just HTML code.

 🚨Note:- Popular Interview Question is "How to convert JSX to React.createElement?" is very important as a React developer
  -> You can set up your own babel configuration using Webpack. Or you can use create-react-app which internally uses Babel for the JSX to JavaScript conversion.
  -> So to convert it to browser understandable JavaScript code, we use a tool like Babel which is a JavaScript compiler/transpiler.
  -> We can use the above JSX in our React code like this:

              import React from "react";
              import ReactDOM from "react-dom";
              class JSXDemo extends React.Component {
                 render() {
                    return <h1>This is JSX</h1>;
                 }
              }
              ReactDOM.render(<JSXDemo />, document.getElementById('root'));

   -> Here, we're returning the JSX from the JSXDemo class component and rendering that on the screen using the ReactDOM.render method.

    -> When the Babel executes the above JSX, it converts it to the following code:

                     class JSXDemo extends React.Component {
                       render() {
                           return React.createElement("h1", null, "This is JSX");
                       }
                     }
   -> Above code still correctly prints the contents to the screen using React.createElement.
   -> This was the old way of writing code in React – but it's tedious / painful to write the React.createElement every time, even for adding a simple div.
  -> So React introduced the JSX way of writing code which makes code easy to write and understand.

Q: What is React.createElement?
A: Every JSX is converted to the React.createElement function call that the browser understands.
Q: Syntac of React.createElement
A: The React.createElement has the following syntax:

                  React.createElement(type, [props], [...children])
  -> Let’s look at the parameters of the createElement function.
        - type can be an HTML tag like h1, div or it can be a React component
        - props are the attributes you want the element to have
        - children contain other HTML tags or can be a component
  -> The React.createElement call will also be converted to the object representation like this:
                {   
                   type: 'h1',   
                   props: {     
                   children: 'This is JSX'   
                   }
                }
 -> You can see this object representation if you assign the JSX to some local variable and log it as shown below:
                 class JSXDemo extends React.Component {
                     render() {
                           const jsx = <h1>This is JSX</h1>;
                           console.log(jsx);
                           return jsx;
                     }
                 }

                ReactDOM.render(<JSXDemo />, document.getElementById('root'));
  -> Here, we've used the JSX like this:
                <h1 id="jsx">This is JSX</h1>
  -> So React, will convert this JSX to the below code:
                React.createElement("h1", { id: "jsx" }, "This is JSX");
  -> If there are any attributes added to the HTML tag as in our case, they will be passed as the second parameter for the React.createElement call. The object representation will look like this:
                { 
                  type: 'h1', 
                  props: { 
                     id: 'jsx',
                     children: 'This is JSX'
                  } 
                }
  -> Now, let's add some complexity to the JSX to see how it's converted to the React.createElement call.
                class JSXDemo extends React.Component {
                    handleOnClick = () => {
                        console.log("clicked");
                    };
                   render() {
                       return (
                           <button id="btn" onClick={this.handleOnClick}>
                          Click Here
                           </button>
                       );
                   }
                }
               ReactDOM.render(<JSXDemo />, document.getElementById("root"));
  -> Here, we've added an onClick handler to the button. For the above code, the React.createElement call will look like this:
               React.createElement("button", {
                      id: "btn", 
                      onClick: function() {}
               }, "Click Here")
  -> JSX is converted to a React.createElement call and it's then converted to its object representation.
              
Q: How to Return Complex JSX
A: Take a look at the below code:
             import React from "react";
             import ReactDOM from "react-dom";

             const App = () => {
                 return (
                  <p>This is first JSX Element!</p>
                  <p>This is another JSX Element</p>
                 );
            };
           const rootElement = document.getElementById("root");
           ReactDOM.render(<App />, rootElement);
  => Here, we're returning two paragraphs from the App component. But if you run the code, you will get  
SyntaxError
  -> We're getting an error because React requires adjacent elements to be wrapped in a parent tag <div>.
  => But there are also other ways of making it work. First, you can try returning it as an array.
  -> This will get the job done, but as you can see in the browser console, you will get a warning saying Warning: Each child in a list should have a unique "key" prop.
NOTE:- Because in React, every element in the array (when displayed using JSX) needs to have a unique key added to it.
 -> We can fix it by adding a unique key for the adjacent elements using key as attribute.
 => The other way to fix it is by using the React.Fragment component
 -> React.Fragment was added in React version 16.2 because we always have to wrap multiple adjacent elements in some tag (like div) inside every JSX returned by a component. But that adds unnecessary div tags.
 -> This is fine most of the time but there are certain cases where it's not fine.
 -> For example, if we're using Flexbox, then there is a special parent-child relationship in Flexbox's structure. And adding divs in the middle makes it hard to keep the desired layout. So using React.Fragment fixes this issue. Fragments let you group a list of children without adding extra nodes to the DOM.
 
Q: How to add JavaScript inside JSX?
A: JSX becomes more useful when we actually add JavaScript code inside it. To add JavaScript code inside JSX, we need to write it in curly brackets. Inside the curly brackets we can only write an expression that evaluates to some value.
Eg: const App = () => {
        const number = 10;
        return (
         <div>
         <p>Number: {number}</p>
         </div>
        );
      };

 -> Inside the curly brackets we can only write an expression that evaluates to some value.
 => Following are the invalid things and cannot be used in a JSX Expression:
       - A for loop or while loop or any other loop
       - A variable declaration
       - A function declaration
       - An if condition
       - An object
 -> We can write arrays in JSX Expressions because <p>{[1, 2, 3, 4]}</p> is finally converted to <p>{1}{2}{3}{4}</p> when rendering (which can be rendered without any issue).
 -> In the case of an object, it’s not clear how the object should be displayed. For example, should it be comma-separated key-value pairs or should it be displayed as JSON? So you will get an error if you try to display the object in a JSX expression. But we can use object properties instead.
 -> Also note that undefined, null, and boolean are not displayed on the UI when used inside JSX.
So if you have a boolean value and you want to display it on the UI you need to wrap it in ES6 template literal syntax.
 -> Eg:- const App = () => {
                const isAdmin = true;
                return (
                  <div>
                    <p>isAdmin is {`${isAdmin}`} </p>
                 </div>
                );
              };

 Conditional Operators in JSX Expressions
 -> We can’t write if conditions in JSX expressions, which you might think of as an issue. But React allows us to write conditional operators, like ternary operators as well as the logical short circuit && operator

Q: How to Nest JSX Expressions?
Eg: const App = () => {
         const number = 10;
         return (
            <div>
              {number > 0 ? (
                <p>Number {number} is positive</p>
              ) : (
               <p>Number {number} is Negative</p>
             )}
          </div>
         );
      };

Q: 🚨How to add Class in JSX? [This use of className instead of class is a frequently asked question in React interviews.]
A: We can add attributes to the JSX elements, for example id and class, the same as in HTML.
 -> Note that in React, we need to use className instead of class.
 -> This is because if you use class instead of className, you will get a warning in the console.
 -> To understand why the warning is being shown, print the object representation of it.
 -> The props object has the class property with a value active. But in JavaScript, class is a reserved keyword so accessing props.class will result in an error.
 -> This is why React decided to use className instead of class.



Q: How to add Comments in JSX?
A: JSX expresssion syntax inside the /* and */ comment symbols

Conclusion:-
  - Every JSX tag is converted to React.createElement call and its object representation.
  - In React, we have to use className instead of class for adding classes to the HTML element
  - All attribute names in React are written in camelCase.
  - undefined, null, and boolean are not displayed on the UI when used inside JSX.

Q: What is Component in React?
A: Components are rightly defined as the essential building blocks of any application created with React, and a single app most often consists of many components. A component is in essence, a piece of the user interface - splitting the user interface into reusable and independent parts, each of which can be processed separately.

Q: Advantage/Aspect of Component
A: Re-usability: 
      -> We can reuse a component used in one area of the application in another area. This speeds up development and helps avoid cluttering of code.
    Nested components:
     ->  A component can contain within itself, several more components.  This helps in creating more complex design and interaction elements.
   Render method: 
     -> In its minimal form, a component must define a render method specifying how it renders to the DOM.
   Passing Props (Properties): 
     -> A component can also receive props. These are properties that its parent passes to specify particular values.

Q: Type of React Components
A: There are two types of components in React:     
      (1) Stateless Functional components: 
            -> These types of components do not have a state of their own and only possess a render method. 
            -> They are also referred to as stateless components. 
            -> They may by way of props (properties), derive data from other components.
      Eg:- Using Arrow Function
              const = () => {
                return (
                  <div>
                      <h1>React Functional Component</h1>
                 </div>
                ) };
            -> The code depicted above creates a functional component App that returns an h1 heading on a web page. Since it is a functional component, it does not hold or manage any state of its own.

      (2) Stateless Class components:
           -> These types of components hold and manage their unique state and have a separate render method to return JSX on the screen. 
           -> They are referred to as stateful components too, as they can possess a state.
      Eg:- class App extends React.Component {
                  constructor(props) {
                      super(props);
                      this.state = { value: '',
                      };
                  }
                 onChange = event => {
                    this.setState({ value: event.target.value });
                 };
                render() {
                  return (
                    <div>
                       <h1>React Class Component</h1>
                       <input
                        value={this.state.value}
                        type="text"
                        onChange={this.onChange}
                      />
                      <p>{this.state.value}</p>
                 </div>
                );
             }
           }
   -> The code mentioned above creates a class component App that extends Component class from React library. 
  -> The class has a constructor that contains the state of the web application. 
  -> onChange function updates the value of the state with the value that the user enters in the input field. render() method outputs the input field to the screen. 
  -> The state gets updated with the value that the user enters, and the value output is presented to the screen inside the <p> tags.

React Nesting Components:-
 -> In React, we can nest components inside within one another.
 ->  This helps in creating more complex User Interfaces. 
 -> The components that are nested inside parent components are called child components. 
 -> Import and Export keywords facilitate nesting of the components.
 -> Export 
      - This keyword is used to export a particular module or file and use it in another module.
 -> Import
      - This keyword is used to import a particular module or file and use it in the existing module.
 -> Components that have to be nested into main component using Export & Import keywords
           import {Class1, Class2} from "./Component";
 -> Importing named values allows the user to import multiple objects from a file.

React Components Lifecycle:-
 -> The React web applications are actually a collection of independent components that run according to the interactions made with them.
 -> Each component in React has a life-cycle that you can monitor and change during its three main phases. 
 -> There are three phases: Mounting, Updating, and Unmounting. 
 -> You can use life-cycle methods to run a part of code at particular times in the process or application. 
 (1) Mounting:
       - Mounting is the phase when the component is mounted on the DOM and then rendered on the webpage. 
       - We call these methods in the following order when an element is being created and inserted into the DOM:
              1. componentWillMount() :
                 -> This function is called right before we mount the component on the DOM. 
                -> So after this method executes, the component gets mounted on the DOM.  
                -> It executes this method before the first render of the React application. 
                -> So all the tasks that have to be done before the component mounts are defined in this method.
             2.  render() : This function mounts the component on the browser. 
             3.  componentDidMount() : 
                 -> We invoke this function right after the component is mounted on the DOM
                 ->  i.e., this function gets called once after the render() function is executed for the first time.
                 ->  Generally, in React applications, we do the API calls within this method.


 (2) Updating:
       - We call the methods in this phase whenever State or Props in a component get updated. 
       - This allows the React application to “react” to user inputs, such as clicks and pressing keys on the keyboard, and ultimately create a responsive web user interface. 
       - These methods are called in the following order to carry on the update of the component:
            1.  componentWillReceiveProps() : We call This function before a component gets its props reassigned.                
            2.  setState() : This function can be called explicitly at any moment. This function is used to update the state of a component.
            3.  shouldComponentUpdate() : 
                  -> This function is called before rendering a component and tells React whether it should update the component on receiving new props or state. 
                  -> It takes the new Props and new State as the arguments and returns whether or not to re-render the component by returning either True or False.
            4. componentWillUpdate() : This function is called once before the render() function is executed after the update of State or Props.
            5.  render() : The component gets rendered when this function is called.
            6. componentDidUpdate() : This function is called once after the render() function is executed after the update of State or Props.
 
 (3) Unmounting:
      - This is the last phase of the life-cycle of the component where the component is unmounted from the DOM. This phase has only one method:
     1. componentWillUnmount() : This function is called once before we remove the component from the page and this marks the end of the life-cycle.

1 Like

JSX stands for JavaScript XML. It is simply a syntax extension of JavaScript. It allows us to directly write HTML in React (within JavaScript code).

React.js there are two main types of components:

  1. functional components and
  2. class components.

Functional components:-
are basically JavaScript functions that take in props as an argument and return a React element to be rendered. They are simpler and less verbose than class components and can be easier to reason about and test. They are also generally faster to render.

Class components:-
on the other hand, are JavaScript classes that extend React. Component class. They have more features and capabilities than functional components, such as state and lifecycle methods. They are also useful for more complex components, such as ones that need to manage an internal state or handle user events.

In general, functional components are recommended over class components unless you specifically need the additional features provided by class components. With the introduction of hooks in React 16.8, functional components can now also handle state and lifecycle methods, making them even more powerful and versatile. I have mentioned below some more reasons to consider Functional Components over Class components.
Reasons:-
There are a few reasons why it’s recommended to use functional components over class components in React:

*Simplicity:- Functional components are simpler and easier to understand than class components. They don’t have the added complexity of lifecycle methods, state, and this binding.

Performance:- Functional components are more performant than class components. They don’t have the added overhead of creating a new instance for each render and also functional components can use the React Hooks which makes it more performant.

Easier to test:- Functional components are easier to test than class components. Because they are just plain JavaScript functions, they can be tested with standard JavaScript testing tools like Jest.

Easier to reuse:- Functional components are easier to reuse than class components. Because they are just plain JavaScript functions, they can be easily reused across different parts of your application.

Easier to understand:-Functional components are easier to reason about than class components. Because they are just plain JavaScript functions, their behavior is more predictable and easier to understand.

1 Like

Creating React Project:-

Step 1:-Install Git

Step 2:- After installation of Git → Go to The Desktop → Right Click on Desktop and Select Git Bash

Step 3:- Run the Command (node --Version) To check Whether Node is installed in your System or not

Step 4:- After that you Run this Command (ls -la) To get a full list of hidden files, The output displays information about the user, size of the file, and date and time of modification.

Step 5:-To create a react app, install react modules by using npx command.

npx create-react-app project name

Step 6:- After creating your react project, move into the folder to perform different operations by using the below command.

cd project name

Step 7:- Open the terminal and type the following command to host the project on the local server.

npm start

1 Like

Creating React Project:-

Step 1:-Install Git

Step 2:- After installation of Git → Go to The Desktop → Right Click on Desktop and Select Git Bash

Step 3:- Run the Command (node --Version) To check Whether Node is installed in your System or not

Step 4:- After that you Run this Command (ls -la) To get a full list of hidden files, The output displays information about the user, size of the file, and date and time of modification.

Step 5:-To create a react app, install react modules by using npx command.

npx create-react-app project name

Step 6:- After creating your react project, move into the folder to perform different operations by using the below command.

cd project name

Step 7:- Open the terminal and type the following command to host the project on the local server.

npm start

1 Like

@abhishek.krspatna Can you share creating react project step in yesterday thread. To keep a better track.

1 Like