My 10 Common Mistakes in HTML & React

Leomahendradev


My 10 Common Mistakes in HTML & React

1. Nesting <div> inside <p> (HTML)

  • Mistake:
    <p>Some text <div>Wrong!</div></p>
    
  • Why? <p> can only contain inline elements, not block-level elements like <div>. I did this a lot.
  • Fix:
    <p>Some text</p>
    <div>Correct!</div>
    

2. Forgetting the key Prop in Lists (React)

  • Mistake:
    {items.map((item) => (
      <li>{item.name}</li>
    ))}
    
  • Why? React needs key to optimize rendering and avoid unnecessary re-renders.
  • Fix:
    {items.map((item) => (
      <li key={item.id}>{item.name}</li>
    ))}
    

3. Using class Instead of className (React)

  • Mistake:
    <div class="container">Wrong in React</div>
    
  • Why? class is a reserved word in JavaScript.
  • Fix:
    <div className="container">Correct in React</div>
    

4. Forgetting alt Attribute for Images (HTML)

  • Mistake:
    <img src="image.jpg">
    
  • Why? Bad for accessibility (screen readers) and SEO.  Seen the consequences in production as images some time don't load.
  • Fix:
    <img src="image.jpg" alt="Description of image">
    

5. Modifying State Directly (React)

  • Mistake:
    const [count, setCount] = useState(0);
    count++; // Wrong
    
  • Why? Directly modifying state doesn’t trigger re-render.
  • Fix:
    setCount(count + 1);
    

6. Using <br> Instead of Proper Spacing (HTML)

  • Mistake:
    <p>Paragraph 1<br><br>Paragraph 2</p>
    
  • Why? Not semantic, hard to style.
  • Fix:
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    

7. Using index as Key in Lists (React)

  • Mistake:
    {items.map((item, index) => (
      <li key={index}>{item.name}</li>
    ))}
    
  • Why? Causes issues when list items are reordered.
  • Fix:
    <li key={item.id}>{item.name}</li>
    

8. Forgetting return in Arrow Functions (React)

  • Mistake:
    const Component = () => (
      <div>Missing return</div>
    );
    
  • Why? Without {}, implicit return works, but with {} you need return.
  • Fix:
    const Component = () => {
      return <div>Fixed</div>;
    };
    

9. Not Closing Tags Properly (HTML)

  • Mistake:
    <img src="image.jpg">
    <input type="text">
    
  • Why? Self-closing tags are required in JSX and recommended in HTML5.
  • Fix:
    <img src="image.jpg" />
    <input type="text" />
    

10. Using Inline Styles in React Without Object Syntax

  • Mistake:
    <div style="color: red;">Wrong</div>
    
  • Why? React requires an object for style.
  • Fix:
    <div style={{ color: "red" }}>Correct</div>

These are mine when I started learning 😏. Let me know yours 

Post a Comment

0 Comments