Wednesday, February 27, 2019

How to console.log in React application using JSX ?

In this tutorial,  we are going to discuss how to perform console.log() in react and react native application inside the render block. Most of the times developer trying to add console.log statement inside the return block of render block, in that case it will not print the statement inside the console rather it will print the results inside the browser screen.

Lets see the below example, where we are using console.log statement inside the return block of render function.

Wrong Method
render() {
  return (
    <div>
      <h1>List of countries</h1>
      console.log(this.props.countries)
    </div>
  );
}

This will not print the expected list in the console. It will just render the string console.log(this.props.countries) in the browser.

Lets see the solution for this example :

Wright Method 

Embed the expression in your JSX.
render() {
  return (
    <div>
      <h1>List of countries</h1>
      { console.log(this.props.countries) }
    </div>
  );
}

Another popular solution widely in use :

Place your console.log before the return().
render() {
   console.log(this.props.countries)
  return (
    <div>
      <h1>List of countries</h1>     
    </div>
  );
}

Also there is another method for this type of scenario, for that you need to create custom component in order to use print console.log statement in react and react native application.

Create custom component for console.log.
const ConsoleLog = ({ children }) => {
  console.log(children);
  return false;
};

Then you can use it like this :
render() {   
  return (
    <div>
      <h1>List of countries</h1>   
      <ConsoleLog>{ this.props.countries }</ConsoleLog>  
    </div>
  );
}


This is all about console.log in react and react native using JSX. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


1 comment: