How to Safely Use console.log() in JSX (React)

Posted on

Safely Using console.log() Inside JSX in React

While developing React applications, we often use console.log() for debugging. Typically, we place it inside event handlers or useEffect() hooks. But what if you want to log something directly within JSX? So, how to use console.log() in JSX or tsx file?

Let’s say you try this inside tsx file or JSX:

console.log('Form data:', form);

This returns undefined jand ust becomes plain text.

The Solution

To safely use console.log() inside JSX, wrap it like this:

{void console.log('form:', form)}

#or

{(() => {
  console.log('form:', form);
  return null;
})()}

This approach works perfectly in JSX because:

  • The arrow function is executed immediately
  • It logs your data using console.log()
  • It returns null, which is safe to render in JSX
  • Nothing is rendered to the UI, and no warning appears in the console

Happy Coding!!!