DEV Community

Cover image for Converting HTML to JSX: Rules of JSX
Sonay Kara
Sonay Kara

Posted on • Edited on

Converting HTML to JSX: Rules of JSX

We will learn what JSX is and the rules of JSX.


JSX is a syntax extension for JavaScript. You can write HTML formatting inside a JavaScript file.

It is based on Web, Html, Css and JavaScript. web developers wrote the content of the page separately as an Html file, the designs as a Css file, and the logic as a JavaScript file.

  • Need to know : JSX is a syntax extension, while React is a JavaScript library.

<div class="wrapper">HTML</div>

Enter fullscreen mode Exit fullscreen mode

//CSS

.wrapper {
   display : flex;
}

Enter fullscreen mode Exit fullscreen mode

function myFunction() {
  document.getElementById("wrapper").innerHTML = "Hello world";
}

Enter fullscreen mode Exit fullscreen mode



But as the Web has become more interactive, logic has become more important. JavaScript was managing Html. Therefore, in React, logic and formatting live together in components.

React component example :

import React, { useState } from "react";

function App() {
  const [formData, setFormData] = useState({
    username: "",
    password: "",
  });

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevState) => ({ ...prevState, [name]: value }));
  };

  return (
    <form>
      <label>
        Username:
        <input
          type="text"
          name="username"
          value={formData.username}
          onChange={handleChange}
        />
      </label>
      <label>
        Password:
        <input
          type="password"
          name="password"
          value={formData.password}
          onChange={handleChange}
        />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode



it is important to keep the rendering markup and logic together to keep an html tag in sync with each other with each editing.

React components are a JavaScript function that contains the markup that React rendering in the browser. React components use a syntax extension called JSX for this markup. JSX is looks like to Html.


The Rules of JSX

1. Return a single root element

To return elements from a component, wrap them with a single parent tag. You can use a or fragment (<></>)

For example div

<div>
  <h1>Hedy Lamarr's Todos</h1>
  <img 
    src="https://picsum.photos/200/300" 
    alt="lorempicsum" 
  >
</div>

For example <></>

<>
   <h1>Hedy Lamarr's Todos</h1>
  <img 
    src="https://picsum.photos/200/300" 
    alt="lorempicsum" 
  />
</>
  • Fragments let you group things without leaving any trace in the browser HTML tree.

2. Close all the tags

In JSX, all tags must be closed. For example, self-closing tags such as img in Html

Example :

<img 
    src="https://picsum.photos/200/300" 
    alt="lorempicsum" 
  />

3. camelCase

In React, many HTML properties are written with camelCase.

Example :

 <img 
    src="https://picsum.photos/200/300" 
    alt="lorempicsum" 
    className="photo"
  />

<button onClick={handleClick}>Click Me</button>


JavaScript in JSX

In JSX, sometimes you will want to add a little JavaScript logic or refer to a dynamic feature inside this markup. In this case, you can use brackets in JSX

  • Passing the string attribute to JSX

When you want to pass a string attribute to JSX, you put it in single or double quotes

Example :

export default function Avatar() {
  return (
    <img
      className="avatar"
      src="https://picsum.photos/200/300"
      alt="lorempicsum"
    />
  );
}



Here, src and alt are being passed as strings. but if you want to specify the src or alt text dynamically, you can use a value from javascript using curly braces instead of double quotes

Example :

export default function Avatar() {
  const avatar = 'https://picsum.photos/200/300';
  const description = 'lorempicsum';
  return (
    <img
      className="avatar"
      src={avatar}
      alt={description}
    />
  );
}


  • Using Curly Braces

It is possible to use JavaScript with curly braces {}. You can use functions, variables and more.

Example :

import React, { useState } from 'react';
     const content = 'Toggle Text';
    function ToggleText() {
      const [isVisible, setIsVisible] = useState(true);

      return (
        <div>
          {isVisible && <p>This text is toggleable</p>}
          <button onClick={() => setIsVisible(!isVisible)}>
            {content}
          </button>
        </div>
      );
    }

    export default ToggleText;

  • Using Double Curlies Braces

React does not require you to use inline styles (CSS classes work great for most cases). But when you need an inline style, you can pass an object to the style attribute. Use double curlies braces.

Example :

export default function TodoList() {
  return (
    <ul style={{
      backgroundColor: 'black',
      color: 'pink'
    }}>
      <li>lorem ipsum</li>
    </ul>
  );
}

  • You see {{ }} in JSX, know that it’s object inside the JSX curlies.

  • Inline style properties should be write as camelCase.


You can move several expressions into one object, and use them in your JSX inside curly braces

const person = {
  name: 'Gregorio Y. Zara',
  theme: {
    backgroundColor: 'red',
    color: 'yellow'
  }
};

export default function TodoList() {
  return (
    <div style={person.theme}>
      <h1>{person.name}'s Todos</h1>
    </div>
  );
}



Conclusion

JSX is an important tool that makes web development processes more effective and practical. With JSX, you can keep the render markup and logic together to keep an html Decal synchronized with each other in every edit.


If you like my articles, you can buy me a coffee :)
Image description

Top comments (1)

Collapse
 
pengeszikra profile image
Peter Vivo • Edited

Sometimes JSX give less usable as simple HTML. For example if you use tailwind and declare some "Component" which is looks like this:

  <template id="frag">
    <figure class="
      fixed 
      top-[5rem] left-[2rem]
      w-[6rem] h-[6rem]
      bg-[url(../sprites/potter3m.png)]
      bg-[length:660%]
      --bg-[position:23.5%_26.7%]
      --bg-[position:42.5%_26.7%]
      --bg-[position:42.5%_36.4%]
      rounded-xl 
      transition-all
      duration-1000
      hover:opacity-30
      hover:duration-200
    "></figure>
  </template>
Enter fullscreen mode Exit fullscreen mode

Then you can use a simple quote string for a multiple line instead JSX need to be use template string to solve that and React use className instead class, which is cause much verbose code.

return (
    <figure className={`
      fixed 
      top-[5rem] left-[2rem]
      w-[6rem] h-[6rem]
      bg-[url(../sprites/potter3m.png)]
      bg-[length:660%]
      --bg-[position:23.5%_26.7%]
      --bg-[position:42.5%_26.7%]
      --bg-[position:42.5%_36.4%]
      rounded-xl 
      transition-all
      duration-1000
      hover:opacity-30
      hover:duration-200
    `}></figure>
);
Enter fullscreen mode Exit fullscreen mode

The worst part, for JSX need to be compile your code, but of course also have advantage: much easier put Component together than simple HTML can do.