Menu

JSX Rules in ReactJS: 5 Essential Rules for Beginners

JSX Rules You Must Follow

The Rules

JSX looks like HTML but has several differences that cause most beginner errors.

Rule 1: Return one parent element

// Wrong — two sibling elements at the top level
return (
  <h1>Dashboard</h1>
  <p>Welcome</p>
);

// Correct
return (
  <div>
    <h1>Dashboard</h1>
    <p>Welcome</p>
  </div>
);

If you do not want an extra div in your HTML, use a Fragment:

return (
  <>
    <h1>Dashboard</h1>
    <p>Welcome</p>
  </>
);

The <>...</> shorthand groups elements without adding anything to the page.

Rule 2: Close every tag

<img src="logo.png" alt="Logo" />
<br />
<input type="text" />

Tags that are self-closing in HTML must have the closing slash in JSX.

Rule 3: Use className instead of class

class is a reserved keyword in JavaScript, so React uses className.

<div className="course-card">React Basics</div>

Rule 4: Attributes use camelCase

HTML

JSX

classclassName
forhtmlFor
onclickonClick
tabindextabIndex
maxlengthmaxLength

Rule 5: Use curly braces for JavaScript values

const progress = 60;
return <p>Progress: {progress}%</p>;

Common Mistakes Beginners Make

  • Writing class instead of className. React warns you in the console.
  • Forgetting the closing slash on <img> or <input>****. This causes a build error.
  • Returning multiple top-level elements. Wrap them in a <div> or a Fragment.
  • Using quotes around a curly-brace value: className="{styleName}" passes the literal text. Write className={styleName}.

ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details