window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-63172957-1');
Sound
Awwwards
</html>
Created by potrace 1.16, written by Peter Selinger 2001-2019
Back to blog
Web Development

React JS Questions & Answers (Part 2) 2021

Article index:

How to use event handlers with React component’s?

Events handling in HTML and React is very similar.

In HTML, the event name we usually declare in lowercase:

<input type="text" onchange='HandleChange' />

In React we use similar syntax but we use a camelCase convention:

<input type="text" onChange={HandleChange} />

The main difference is that in HTML you can return false to prevent default behaviour but in react you must call preventDefault().

HTML

<input type="text" onchange='console.log("change occured."); return false;' />

React

<input type="text" onChange={HandleChange} />

 

function handleClick(event) {
  event.preventDefault()
  console.log('The link was clicked.')
}

How to bind methods or event handlers in JSX callbacks?

Functional approach

Let’s define a function – which can be normal or arrow – for the change event of the input field. Now the function can be passed to the onChange attribute (JSX named attribute) of the input field.

const App = () => {
  const handleChange = event => {
    console.log(event);
  };
  return (
    <div>
      <h1>My Hacker Stories</h1>
      <label htmlFor="search">Search: </label>
      <input type="text" onChange={handleChange} />
   </div>
   );
}

Constructor approach

When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class.

class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleChange= this.handleChange.bind(this);
  }
  handleChange() {
    console.log('Click happened');
  }
  render() {
    return <input type="text" onChange={this.handleChange} />;
  }
}

In JavaScript, class methods are not bound by default. If you forget to bind this.handleChange and pass it to onClick, this will be undefined when the function is actually called.

But there is a way you can get around this as you can use an arrow function in the callback:

class Foo extends React.Component{
  handleChange() {
    console.log('Click happened');
  }
  render() {
    return <input type="text" onChange={() => this.handleChange()} />;
  }
}

What is a synthetic event in React?

Please look at the example below that we have taken from the previous question.

const App = () => {
  const handleChange = event => {
   console.log(event.target.value); //event - is not real but a synthetic event 
  };
  return ( ... );
};

As you see the synthetic event looks similar to the browser’s native event but in reality, it is essentially a cross-browser wrapper around the browser’s native event.

It has more functions that are useful to prevent native browser behaviour (e.g. refreshing a page after the user clicks a form’s submit button). React normalizes its events so that they have consistent properties across different browsers.

What is an inline conditional expression in React?

It’s a conditional rendering included directly in JSX syntax.

With JavaScript’s ternary operator, we can inline conditional state as a conditional rendering JSX:

{isLoading ? (<p>Loading ...</p>) : (<p>Loaded</p>) }

// OR SHORTHAND

{isLoading  &amp;&amp;
      <h2>
          You have {messages.length} unread messages.
      </h2>
      :
      <h2>
          You don't have unread messages.
      </h2>
}

This feature can be quite powerful because it gives you the ability to conditionally render JSX. It’s yet another tool in React to make your UI more dynamic.

What is Virtual DOM?

The Virtual DOM is a technique that React uses to optimize interacting with the browser. It is an in-memory representation of Real DOM. React keeps a copy of the DOM representation, for what concerns the React rendering: the Virtual DOM.

The DOM (Document Object Model) is a Tree representation of the page, starting from thetag, going down into every child, which are called nodes. The DOM has an API that you can use to traverse it, access every single node, filter them, modify them with JavaScript.

Every time the DOM changes, the browser has to do two intensive operations: repaint and reflow.

React uses a Virtual DOM to help the browser use less resources when changes need to be done on a page

What are the different phases of component lifecycle?

The component lifecycle has three distinct lifecycle phases:

  • Mounting
  • Updating
  • Unmounting

Mounting

constructor – > render -> componentDidUpdate

The process by which React creates a component and renders its content for the first time is called mounting, and there are three commonly used methods that components implement to participate in the mounting.

constructor
React create a new instance of a component, which gives the component an opportunity to receive the props, define its state data, and perform other preparatory work.

render
The component provides React with the content that will be added to the DOM.

componentDidMount
It is invoked immediately after React inserts a component into the DOM. The updated DOM is now available for access, which means that this method is the best place for initializing other JavaScript libraries that need access to that DOM.


var HelloMessage = React.createClass({ 
    componentDidMount: function() { 
        console.log('componentDidMount'); 
        //opening an AJAX function here
    }, 
    render: function() { 
        console.log('render'); 
        return <h2>{this.props.message}</h2>; 
    } 
});

Updating

render -> componentDidUpdate

That phase invokes calling the render method to get content from the component and then calling the componentDidUpdate after the reconciliation process is complete.

After the initial rendering that is performed during the mounting phase, any subsequent calls to the render method will be followed by a call to the componentDidUpdate method once React has completed the reconciliation process and updated the DOM.

componentDidUpdate
The method is called immediately after React updates the DOM. It gets these two arguments:

  • prevProps: The previous properties object
  • prevState: The previous state object

The main use of the componentDidUpdate method is to directly manipulate the HTML elements in the
DOM.


var HelloMessage = React.createClass({ 
    componentDidUpdate: function (prevProps, prevState) { 
        console.log("componentDidUpdate Message Component");
    },
    render: function() { 
        console.log('render'); 
        return <h2>{this.props.message}</h2>; 
    } 
});

After componentDidUpdate() is called, the updating cycle ends.

Unmounting

React offers only one method for this phase, which is componentWillUnmount . When a component is about to be destroyed, React will call it.

componentWillUnmount
This method is useful for cleaning up any data that is created during the component’s mounting or updating phases. It provides components with the opportunity to release resources, close network connections, and stop any asynchronous tasks.


var HelloMessage = React.createClass({ 
    componentWillUnmount: function () { 
        console.log("componentDidUpdate Message Component");
       //closing an AJAX connection here
    },
    render: function() { 
        console.log('render'); 
        return <h2>{this.props.message}</h2>; 
    } 
});



Back to blog

</html>
Wordpress Developer Loader, Web Developer Loader , Front End Developer Loader Jack is thinking