React Feature

By ukmodak | April 29th 2021 06:09:08 AM | viewed 79 times

React JSX

As we have already seen that, all of the React components have a render function. The render function specifies the HTML output of a React component. JSX(JavaScript Extension), is a React extension which allows writing JavaScript code that looks like HTML. In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e., transpilers like babel) to transform HTML-like syntax into standard JavaScript objects that a JavaScript engine will parse.

JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file where you write JavaScript code, then preprocessor will transform these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children.

JSX File

<div>Hello JavaTpoint</div>  

Corresponding Output

   React.createElement("div", null, "Hello JavaTpoint");  

Nested Elements in JSX

To use more than one element, you need to wrap it with one container element. Here, we use div as a container element which has three nested elements inside it.

App.jsx=>

    import React, { Component } from 'react';  
    class App extends Component{  
       render(){  
          return(  
             <div>  
                <h1>JavaTpoint  
              <h2>Training Institutes  
                <p>This website contains the best CS tutorials.

</div> ); } } export default App;

JSX Attributes

JSX use attributes with the HTML elements same as regular HTML. JSX uses camelcase naming convention for attributes rather than standard naming convention of HTML such as a class in HTML becomes className in JSX because the class is the reserved keyword in JavaScript. We can also use our own custom attributes in JSX. For custom attributes, we need to use data- prefix. In the below example, we have used a custom attribute data-demoAttribute as an attribute for the

tag.

    import React, { Component } from 'react';  
    class App extends Component{  
       render(){  
          return(  
              <div>  
                  <h1>JavaTpoint  
               <h2>Training Institutes  
                  <p data-demoAttribute = "demo">This website contains the best CS tutorials.

</div> ); } } export default App;

In JSX, we can specify attribute values in two ways:

Step-1:As String Literals: We can specify the values of attributes in double quotes:

import React, { Component } from 'react';  
class App extends Component{  
   render(){  
      return(  
         <div>  
            <h1 className = "hello" >JavaTpoint  
            <p data-demoAttribute = "demo">This website contains the best CS tutorials.

</div> ); } } export default App;

Step-1:As Expressions: We can specify the values of attributes as expressions using curly braces {}:

    import React, { Component } from 'react';  
    class App extends Component{  
       render(){  
          return(  
             <div>  
                <h1 className = "hello" >{25+20}</h1>  
              </div>  
          );  
       }  
    }  
    export default App;  

JSX Comments

    import React, { Component } from 'react';  
    class App extends Component{  
       render(){  
          return(  
             <div>  
                <h1 className = "hello" >Hello JavaTpoint</h1>  
            {/* This is a comment in JSX */}   
              </div>  
          );  
       }  
    }  
    export default App;  

JSX Styling

React always recommends to use inline styles. To set inline styles, you need to use camelCase syntax. React automatically allows appending px after the number value on specific elements. The following example shows how to use styling in the element.

    import React, { Component } from 'react';  
    class App extends Component{  
       render(){  
         var myStyle = {  
             fontSize: 80,  
             fontFamily: 'Courier',  
             color: '#003300'  
          }  
          return (  
             <div>  
                <h1 style = {myStyle}>www.javatpoint.com</h1>  
              </div>  
          );  
       }  
    }  
    export default App;  
   import React, { Component } from 'react';  
    class App extends Component{  
       render(){  
          var i = 5;  
          return (  
             <div>  
                <h1>{i == 1 ? 'True!' : 'False!'}</h1>  
              </div>  
          );  
       }  
    }  
    export default App;  

Components

Earlier, the developers write more than thousands of lines of code for developing a single page application. These applications follow the traditional DOM structure, and making changes in them was a very challenging task. If any mistake found, it manually searches the entire application and update accordingly. The component-based approach was introduced to overcome an issue. In this approach, the entire application is divided into a small logical group of code, which is known as components.

A Component is considered as the core building blocks of a React application. It makes the task of building UIs much easier. Each component exists in the same space, but they work independently from one another and merge all in a parent component, which will be the final UI of your application.

Every React component have their own structure, methods as well as APIs. They can be reusable as per your need. For better understanding, consider the entire UI as a tree. Here, the root is the starting component, and each of the other pieces becomes branches, which are further divided into sub-branches.

In ReactJS, we have mainly two types of components. They are

  • Functional Components
  • Class Components

Functional Components

Let's start with a simple example of a Functional Component in React defined as App which returns JSX:.


    import React from 'react';
 
function App() {
  const greeting = 'Hello Function Component!';
 
  return <h1  > {greeting} < /h1 > ;
}
 
export default App;

import React from 'react';
 
function App() {
  return <Headline />;
}
 
function Headline() {
  const greeting = 'Hello Function Component!';
 
  return <h1>{greeting}</h1>;
}
 
export default App;

REACT FUNCTION COMPONENT with PROPS

Let's learn about a React Function Component with props. In React, props are used to pass information from component to component.

import React from 'react';
 
function App() {
  const greeting = 'Hello Function Component!';
 
  return <Headline value={greeting} />;
}
 
function Headline(props) {
  return <h1>{props.value}</h1>;
}

or

function Headline({ value }) {
  return <h1>{value}</h1>;
}
 
export default App;

REACT ARROW FUNCTION COMPONENT

With the introduction of JavaScript ES6, new coding concepts were introduced to JavaScript and therefore to React. For instance, a JavaScript function can be expressed as lambda (arrow function). That's why a Function Component is sometimes called Arrow Function Components (or maybe also Lambda Function Component). Let's see our refactored React Component with an Arrow Function:

import React from 'react';
 
const App = () => {
  const greeting = 'Hello Function Component!';
 
  return <Headline value={greeting} />;
};
 
const Headline = ({ value }) => {
  return <h1>{value}</h1>;
};

or

function Headline({ value }) {
  return <h1>{value}</h1>;
}
 
export default App;

REACT STATELESS FUNCTION COMPONENT

Note Every component we have seen so far can(all above) be called Stateless Function Component. They just receive an input as props and return an output as JSX: (props) => JSX. The input, only if available in form of props, shapes the rendered output. These kind of components don't manage state and don't have any side-effects (e.g. accessing the browser's local storage). People call them Functional Stateless Components, because they are stateless and expressed by a function. However, React Hooks made it possible to have state in Function Components.

REACT FUNCTION COMPONENT: STATE

React Hooks made it possible to use state (and side-effects) in Function Components. Finally we can create a React Function Component with state! Let's say we moved all logic to our other Function Component and don't pass any props to it:

import React, { useState } from 'react';
 
const App = () => {
  return <Headline />;
};
 
const Headline = () => {
  const [greeting, setGreeting] = useState(
    'Hello Function Component!'
  );
  
  // setGreeting == function
  // greeting  = variavle inside function 
 
  return (
    <div>
      <h1>{greeting}</h1>
 
      <input
        type="text"
        value={greeting}
        onChange={event => setGreeting(event.target.value)}
      />
    </div>
  );
};

REACT FUNCTION COMPONENT: EVENT HANDLER

In the previous example you have used an onChange event handler for the input field. That's appropriate, because you want to be notified every time the internal value of the input field has changed. In the case of other HTML form elements, you have several other React event handlers at your disposal such as onClick, onMouseDown, and onBlur.


import React, { useState } from 'react';
 
const App = () => {
  return <Headline />;
};
 
const Headline = () => {
  const [greeting, setGreeting] = useState(
    'Hello Function Component!'
  );
 
  const handleChange = event => setGreeting(event.target.value);
 
  return (
    <div>
      <h1>{greeting}</h1>
 
      <input type="text" value={greeting} onChange={handleChange} />
    </div>
  );
};
 
export default App;

REACT FUNCTION COMPONENT: CALLBACK FUNCTION

Everything happens in our Child Function Component. There are no props passed to it, even though you have seen before how a string variable for the greeting can be passed from the Parent Component to the Child Component. Is it possible to pass a function to a component as prop as well? Somehow it must be possible to call a component function from the outside! Let's see how this works:

import React, { useState } from 'react';
 
const App = () => {
  const [greeting, setGreeting] = useState(
    'Hello Function Component!'
  );
 
  const handleChange = event => setGreeting(event.target.value);
 
  return (
    <Headline headline={greeting} onChangeHeadline={handleChange} />
  );
};
 
const Headline = ({ headline, onChangeHeadline }) => (
  <div>
    <h1>{headline}</h1>
 
    <input type="text" value={headline} onChange={onChangeHeadline} />
  </div>
);
 
export default App;

Let's introducing a Sibling Component for the Headline component. It could be an abstract Input component:

import React, { useState } from 'react';
 
const App = () => {
  const [greeting, setGreeting] = useState(
    'Hello Function Component!'
  );
 
  const handleChange = event => setGreeting(event.target.value);
 
  return (
    <div>
      
 
      <Input value={greeting} onChangeInput={handleChange}>
        Set Greeting:
      </Input>
    </div>
  );
};
 
const Headline = ({ headline }) => <h1>{headline}</h1>;
 
const Input = ({ value, onChangeInput, children }) => (
  <label>
    {children}
    <input type="text" value={value} onChange={onChangeInput} />
  </label>
);
 
export default App;

Async Function in Component with React

import React from 'react';
 
const App = () => {
  const sayHello = () =>
    setTimeout(() => console.log('Hello'), 1000);
 
  return <Button handleClick={sayHello} />;
};
 
const Button = ({ handleClick }) => (
  <button type="button" onClick={handleClick}>
    Button
  </button>
);
 
export default App;
import React, { useState } from 'react';
 
const App = () => {
  const [count, setCount] = useState(0);
 
  const handleIncrement = () =>
    setTimeout(
      () => setCount(currentCount => currentCount + 1),
      1000
    );
 
  const handleDecrement = () =>
    setTimeout(
      () => setCount(currentCount => currentCount - 1),
      1000
    );
 
  return (
    <div>
      <h1>{count}</h1>
 
      <Button handleClick={handleIncrement}>Increment</Button>
      <Button handleClick={handleDecrement}>Decrement</Button>
    </div>
  );
};
 
const Button = ({ handleClick, children }) => (
  <button type="button" onClick={handleClick}>
    {children}
  </button>
);
 
export default App;

REACT FUNCTION COMPONENT: LIFECYCLE

If you have used React Class Components before, you may be used to lifecycle methods such as componentDidMount, componentWillUnmount and shouldComponentUpdate. You don't have these in Function Components, so let's see how you can implement them instead.

import React, { useState, useEffect } from 'react';
 
const App = () => {
  const [count, setCount] = useState(0);
 
  const handleIncrement = () =>
    setCount(currentCount => currentCount + 1);
 
  const handleDecrement = () =>
    setCount(currentCount => currentCount - 1);
 
  useEffect(() => setCount(currentCount => currentCount + 1), []);
 
  return (
    <div>
      <h1>{count}</h1>
 
      <button type="button" onClick={handleIncrement}>
        Increment
      </button>
      <button type="button" onClick={handleDecrement}>
        Decrement
      </button>
    </div>
  );
};
 
export default App;

import React, { useState, useEffect } from 'react';
 
const App = () => {
  const initialCount = +localStorage.getItem('storageCount') || 0;
  const [count, setCount] = useState(initialCount);
 
  const handleIncrement = () =>
    setCount(currentCount => currentCount + 1);
 
  const handleDecrement = () =>
    setCount(currentCount => currentCount - 1);
 
  useEffect(() => localStorage.setItem('storageCount', count));
 
  return (
    <div>
      <h1>{count}</h1>
 
      <button type="button" onClick={handleIncrement}>
        Increment
      </button>
      <button type="button" onClick={handleDecrement}>
        Decrement
      </button>
    </div>
  );
};
 
export default App;

REACT FUNCTION COMPONENT: REF

A React Ref should only be used in rare cases such as accessing/manipulating the DOM manually (e.g. focus element), animations, and integrating third-party DOM libraries (e.g. D3). If you have to use a Ref in a Function Component, you can define it within the component. In the following case, the input field will get focused after the component did mount:

import React, { useState, useEffect, useRef } from 'react';
 
const App = () => {
  const [greeting, setGreeting] = useState('Hello React!');
 
  const handleChange = event => setGreeting(event.target.value);
 
  return (
    <div>
      <h1>{greeting}</h1>
 
      <Input value={greeting} handleChange={handleChange} />
    </div>
  );
};
 
const Input = ({ value, handleChange }) => {
  const ref = useRef();
 
  useEffect(() => ref.current.focus(), []);
 
  return (
    <input
      type="text"
      value={value}
      onChange={handleChange}
      ref={ref}
    />
  );
};
 
export default App;

REACT FUNCTION COMPONENT: PROPTYPES

PropTypes can be used for React Class Components and Function Components the same way. Once you have defined your component, you can assign it PropTypes to validate the incoming props of a component:

import React from 'react';
import PropTypes from 'prop-types';
 
const App = () => {
  const greeting = 'Hello Function Component!';
 
  return <Headline value={greeting} />;
};
 
const Headline = ({ value }) => {
  return <h1>{value}</h1>;
};
 
Headline.propTypes = {
  value: PropTypes.string.isRequired,
};
 
export default App;
import React from 'react';
 
const App = () => {
  const greeting = 'Hello Function Component!';
 
  return <Headline headline={greeting} />;
};
 
const Headline = ({ headline }) => {
  return <h1>{headline}</h1>;
};
 
Headline.defaultProps = {
  headline: 'Hello Component',
};
 
export default App;

REACT FUNCTION COMPONENT: TYPESCRIPT

If you are looking for a type system for your React application, you should give TypeScript for React Components a chance. A strongly typed language like TypeScript comes with many benefits for your developer experience ranging from IDE support to a more robust code base. You may wonder: How much different would a React Function Component with TypeScript be? Check out the following typed component:

import React, { useState } from 'react';
 
const App = () => {
  const [greeting, setGreeting] = useState(
    'Hello Function Component!'
  );
 
  const handleChange = event => setGreeting(event.target.value);
 
  return (
    <Headline headline={greeting} onChangeHeadline={handleChange} />
  );
};
 
const Headline = ({
  headline,
  onChangeHeadline,
}: {
  headline: string,
  onChangeHeadline: Function,
}) => (
  <div>
    <h1>{headline}</h1>
 
    <input type="text" value={headline} onChange={onChangeHeadline} />
  </div>
);
 
export default App;
It only defines the incoming props as types. However, most of the time type inference just works out of the box. For instance, the use State Hook from the App component doesn't need to be typed, because from the initial value the types for greeting and setGreeting are inferred.

If you want to know how to

REACT FUNCTION COMPONENT VS CLASS COMPONENT

Functional Components, because they are more lightweight than Class Components and offer a sophisticated API for reusable yet encapsulated logic with React Hooks.

// Class Component
 
class App extends React.Component {
  constructor(props) {
    super(props);
 
    this.state = {
      value: localStorage.getItem('myValueInLocalStorage') || '',
    };
  }
 
  componentDidUpdate() {
    localStorage.setItem('myValueInLocalStorage', this.state.value);
  }
 
  onChange = event => {
    this.setState({ value: event.target.value });
  };
 
  render() {
    return (
      <div>
        <h1>Hello React ES6 Class Component!</h1>
 
        <input
          value={this.state.value}
          type="text"
          onChange={this.onChange}
        />
 
        <p>{this.state.value}</p>
      </div>
    );
  }
}
 
// Function Component
 
const App = () => {
  const [value, setValue] = React.useState(
    localStorage.getItem('myValueInLocalStorage') || '',
  );
 
  React.useEffect(() => {
    localStorage.setItem('myValueInLocalStorage', value);
  }, [value]);
 
  const onChange = event => setValue(event.target.value);
 
  return (
    <div>
      <h1>Hello React Function Component!</h1>
 
      <input value={value} type="text" onChange={onChange} />
 
      <p>{value}</p>
    </div>
  );
};

In Class Components.....

Map(data iteration)

Class components are more complex than functional components. It requires you to extend from React. Component and create a render function which returns a React element. You can pass data from one class to other class components. You can create a class by defining a class that extends Component and has a render function. Valid class component is shown in the below example.

In this example, we are creating the list of unordered elements, where we will dynamically insert StudentName for every object from the data array. Here, we are using ES6 arrow syntax (=>) which looks much cleaner than the old JavaScript syntax. It helps us to create our elements with fewer lines of code. It is especially useful when we need to create a list with a lot of items.

    import React, { Component } from 'react';  
    class App extends React.Component {  
     constructor() {  
          super();  
          this.state = {  
             data:   
             [  
                {             
                   "name":"Abhishek"             
                },  
                {            
                   "name":"Saharsh"             
                },  
                {    
                   "name":"Ajay"          
                }  
             ]  
          }  
       }  
       render() {  
          return (  
             <div>  
                  
                <ul>            
                    {this.state.data.map((item) => <List data = {item} />)}           
                </ul> 
             </div>  
          );  
       }  
    }  
    class StudentName extends React.Component {  
       render() {  
          return (  
             <div >  
                <h1>Student Name Detail</h1>  
             </div>  
          );  
       }  
    }  
    class List extends React.Component {  
       render() {  
          return (  
             <ul>            
                <li>{this.props.data.name}</li>   
             </ul>  
          );  
       }  
    }  
    export default App;  

State

React State

The state is an updatable structure that is used to contain data or information about the component. The state in a component can change over time. The change in state over time can happen as a response to user action or system event. A component with the state is known as stateful components. It is the heart of the react component which determines the behavior of the component and how it will render. They are also responsible for making a component dynamic and interactive.

A state must be kept as simple as possible. It can be set by using the setState() method and calling setState() method triggers UI updates. A state represents the component's local state or information. It can only be accessed or modified inside the component or by the component directly. To set an initial state before any interaction occurs, we need to use the getInitialState() method.

Defining State

To define a state, you have to first declare a default set of values for defining the component's initial state. To do this, add a class constructor which assigns an initial state using this.state. The 'this.state' property can be rendered inside render() method.

The below sample code shows how we can create a stateful component using ES6 syntax.

    import React, { Component } from 'react';  
    class App extends React.Component {  
     constructor() {  
          super();        
          this.state = { displayBio: true };  
          }  
          render() {  
              const bio = this.state.displayBio ? (  
                  <div>  
                       <p><h3>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multinational companies to teach our campus students. </h3> </p>   
                </div>  
                  ) : null;  
                  return (  
                       <div>  
                           <h1> Welcome to JavaTpoint!!  </h1>  
                          { bio }   
                      </div>  
                  );  
         }  
    }  
    export default App;  

To set the state, it is required to call the super() method in the constructor. It is because this.state is uninitialized before the super() method has been called.

Changing the State

We can change the component state by using the setState() method and passing a new state object as the argument. Now, create a new method toggleDisplayBio() in the above example and bind this keyword to the toggleDisplayBio() method otherwise we can't access this inside toggleDisplayBio() method.

    this.toggleDisplayBio = this.toggleDisplayBio.bind(this);

In this example, we are going to add a button to the render() method. Clicking on this button triggers the toggleDisplayBio() method which displays the desired output.

    import React, { Component } from 'react';  
    class App extends React.Component {  
     constructor() {  
          super();        
          this.state = { displayBio: false };    // declare function variavle  
          console.log('Component this', this);  
          this.toggleDisplayBio = this.toggleDisplayBio.bind(this);   // bind the function toggleDisplayBio  
          }  
          toggleDisplayBio(){    // declare the function toggleDisplayBio
              this.setState({displayBio: !this.state.displayBio});  
              }  
          render() {  
              return (  
                  <div>  
                      <h1>Welcome to JavaTpoint!!</h1>  
                      {  
                          this.state.displayBio ? (   
                              <div>  
                                  <p><h4>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multinational companies to teach our campus students.</h4></p>  
                                  <button onClick={this.toggleDisplayBio}> Show Less </button>  
                            </div>  
                              ) : (  
                                  <div>  
                                      <button onClick={this.toggleDisplayBio}> Read More </button>  
                                  </div>  
                              )  
                      }  
                  </div>  
            )  
        }  
    }  
    export default App;  
bONEandALL