R

React Handbook

Clean • Professional

React JSX Basics — Top Interview Questions & Answers

2 minute

JSX Basics - Interview Questions & Answers

Ques 1: What is JSX in React?

Ans: JSX (JavaScript XML) allows writing HTML-like code inside JavaScript. It helps describe the UI structure and makes React code more readable and declarative.

Example:

const element = <h1>Hello, React!</h1>;

Ques 2: Why does React use JSX instead of pure JavaScript?

Ans: JSX provides better readability, allows mixing HTML and JS logic, makes UI structure intuitive, and improves performance after compilation with Babel.

Ques 3: How does JSX work behind the scenes?

Ans: JSX is compiled by Babel into React.createElement() calls, which return virtual DOM elements.

Example:

<h1>Hello</h1>
// Compiles to
React.createElement('h1', null, 'Hello');

Ques 4: Can you use JSX without importing React (React 17+)?

Ans: Yes. Since React 17, importing React is no longer required to use JSX because the new JSX transform automatically imports required functions.

Ques 5: What are JSX expressions in React?

Ans: JSX allows embedding JavaScript expressions inside {}.

Example:

const name = "React";
<h1>Hello, {name}</h1>;

Ques 6: Can JSX return multiple elements?

Ans: No, JSX must have one parent element. Use a wrapper like <div> or React Fragments (<>...</>).

Example:

<>
  <h1>Title</h1>
  <p>Subtitle</p>
</>

Ques 7: What is the difference between JSX and HTML?

JSXHTML
Written inside JSWritten separately
Uses camelCase attributesUses lowercase attributes
Example: classNameExample: class

Ques 8: What are JSX attributes?

Ans: JSX attributes are similar to HTML but written in camelCase.

Example:

<img src="logo.png" alt="logo" />
<button onClick={handleClick}>Click</button>

Ques 9: How do you apply inline styles in JSX?

Ans: Inline styles use an object with camelCased property names.

Example:

<h1 style={{ color: 'blue', fontSize: '20px' }}>Styled Text</h1>

Ques 10: Can JSX include conditional logic?

Ans: Yes, using ternary operators or logical &&.

Example:

{isLoggedIn ? <h1>Welcome</h1> : <h1>Please Login</h1>}

Ques 11: What are JSX fragments?

Ans: Fragments (<></>) let you group multiple elements without adding extra DOM nodes.

Example:

<>
  <p>Item 1</p>
  <p>Item 2</p>
</>

Ques 12: How can you comment inside JSX?

Ans: Use {/* comment */} syntax inside JSX.

Example:

<div>
  {/* This is a comment */}
</div>

Ques 13: What happens if JSX is not written properly?

Ans: JSX will fail to compile because it must follow XML-like syntax — all tags must be properly closed and wrapped in one parent element.

Ques 14: Can JSX be stored in a variable?

Ans: Yes. JSX is just syntactic sugar for React elements.

Example:

const element = <h1>Hello</h1>;

Ques 15: Is JSX mandatory in React?

Ans: No, JSX is optional. You can write components using React.createElement() directly, but JSX is preferred for readability.

Article 0 of 0