Отличие jsx от html

Very Confusing differences between JSX and HTML

When I work with both JSX and HTML, I get tripped up by subtle differences between the two languages. In this post, I’ll share the differences that I find Very Confusing.

🚶🏽‍♂️ Before we get started, I want to clarify some definitions. You can skip this first half if you’re already familiar with React! 🏃🏻‍♀️

JSX is the syntax that goes in your React components * .

* (You can use JSX with frameworks other than React, but that’s beyond the scope of this post.)

import React from "react"; export const MyReactComponent = () => ( div> h1>Hi there! This is My Component.h1> h2>Isn't it cool?h2> div> );

The syntax after MyReactComponent = () => ( is JSX. It looks like HTML. That’s intentional!

When you run your React app, the rendered component will look similar to what this raw HTML page would render:

DOCTYPE html> html> body> div> h1>Hi there! This is My HTML page.h1> h2>Isn't it cool?h2> div> body> html>

I learned HTML before JSX, so I use HTML as a mental model of how JSX works. I look at the JSX in my React component and imagine an equivalent HTML page. (I wonder if it’s the other way around for developers who learned JSX first 🤔?)

Since JSX and HTML are so similar, in the few situations where they differ, my mental model model can be really deceptive 😱.

Ok but like what actually is JSX?

Fair question. When I say JSX in this post, I’m hand-wavily referring to JSX + React + ReactDOM + the DOM.

In the purest sense, JSX is just a language that compiles into JS. If you compile the code sample above for React with Babel,

import React from "react"; export const MyReactComponent = () => React.createElement( "div", null, React.createElement("h1", null, "Hi there! This is My Component."), React.createElement("h2", null, "Isn't it cool?") );

This isn’t HTML in any sense. JSX never * * gets «converted» to HTML, that’s just a helpful mental model. Instead, JSX gets compiled to this tree of JS function calls.

At runtime, React magically transforms that tree into actual DOM elements. In other words, you can loosely imagine React as the «bridge» that gets your JSX to show up as actual DOM elements in the browser.

This is a diagram showing how JSX and HTML are transformed into elements the DOM. The DOM is what you

In summary, JSX and HTML look similar as source code, and they create similar end results in the DOM.

Differences between JSX and HTML

Ok! With all those definitions out of the way 😅, I’m going to talk about the differences between JSX and HTML that Very Confuse me.

If you have this element in JSX, what do you think it does?

Intuitive meaning:

Let’s look at some other syntax to see if we can figure out what this means. There are two similar syntaxes, one in JS and one in HTML.

const disabled = false; // or true const props =  disabled >; // is equivalent to const disabled = false; // or true const props =  disabled: disabled >;

Which one do you think JSX follows?

Actual meaning:

When debugging JSX, I often find it helpful to compile the JSX to JS. (Is that a sign of a leaky abstraction 🤔?)

button disabled />; // compiles to React.createElement("button",  disabled: true >);

Turns out that JSX matches the HTML behavior. A prop with no specified value gets passed as true . This wasn’t a difference between JSX and HTML after all.

Usually I introduce boolean props accidentally when refactoring code. I’ll start with something like this:

const props =  name, onClick: () => setName(name), placeholderText: "Enter your name", >; NameDisplay . props> />;

and I’ll decide to rewrite it without the <. props>spread:

NameDisplay name onClick=() => setName(name)> placeholderText="Enter your name" />

But! I forget to expand name into name= .

Using ESLint or TypeScript is helpful in this situation, since it will warn me that I never used the variable name until I write name= .

Sort of. It will work 🤷🏼‍♂️. However, if you’re using TypeScript, you’ll get a compilation error saying that you can’t pass a string for maxLength .

This is different from HTML, where maxlength=»10″ is acceptable syntax.

ℹ️ attributes and props are analogous:

In HTML, all attributes are strings (well, close enough). So if you want to set an attribute to a number, you set maxlength=»10″ and internally the DOM will transform that «10» string into a number.

JSX, however, supports multiple ways of passing props. There’s maxLength=»10″ and maxLength= .

  • maxLength= passes the JS expression between <> , which is 10 in this case.
  • maxLength=»10″ passes a string.
    • You can think of it as shorthand for maxLength= .
    input maxLength="10" />; // compiles to React.createElement("input",  maxLength: "10", >); input maxLength=10> />; // compiles to React.createElement("input",  maxLength: 10, >); input maxLength="10"> />; // compiles to React.createElement("input",  maxLength: "10", >);

    You can imagine that React.createElement(«input», . ) has a type definition that only accepts certain props:

    interface InputElementProps  maxLength?: number; >

    Which means that < maxLength: "10" >would fail the type check, like we saw in the original error message for .

    A self-closing tag is a tag that doesn’t need a corresponding closing tag.

    The syntax ends with/> , like .

    The behavior of the/> syntax is pretty different between JSX and HTML. I’ve found this difference most confusing when I’ve been working with JSX for a while, then go back to editing a legacy HTML template, since I’ll expect the HTML to behave the same way JSX does. My HTML page won’t throw a compilation error to tell me I did it wrong, either 😔.

    It’s the same behavior, regardless of the element’s type. ( div , br , MyComponent , circle , . ) That’s it.

    First off, if you look back at XHTML (we don’t talk about XHTML) or HTML4, the behavior is different. I’ll ignore this fact and only cover modern HTML (i.e., HTML5, documents that start with ).

    In HTML, the/> syntax is usually meaningless, but it depends on specifically what element you use it on.

    • Normal elements. This set includes elements that can have children, such as div , span and h1 ..
      • This syntax for normal elements is invalid HTML. However, browsers will treat the tags like opening tags. So
        will be treated as
        , likely causing you to forget the (still necessary) closing

        tag.

      • This syntax for void elements is valid HTML, but has no effect. That means

        and


        are equivalent, and neither require a closing tag.

      • In this situation, the syntax does denote a self-closing tag, following the behavior we’ve learned from JSX. So, is the same as .

      I wouldn’t recommend memorizing that, or anything. Just be aware that the/> syntax in HTML is haunted and in JSX it is simple 😂. And also, if you write a blog post and start referencing the HTML spec, you’ll have a bad time writing out all the edge cases.

      There are plenty more differences between JSX and HTML, and I recommend reading the official React documentation for a more broad overview: JSX in Depth. If you’re interested in differences between React’s DOM and the DOM, check out DOM Elements.

      Anyway. It’s a scary world out there. Be careful!

      Источник

      HTML vs JSX – What’s the Difference?

      Kolade Chris

      Kolade Chris

      HTML vs JSX – What's the Difference?

      HTML vs JSX

      Hypertext Markup Language (HTML) is the standard language for documents that determine the structure of a web page.

      HTML is a very important language in web development. Your code is either in HTML originally or compiles to it so browsers can read it.

      JSX, on the other hand, means JavaScript Syntax Extension or JavaScript XML as some like to put it.

      It was created as a syntactic sugar for React.createElement() . It is an extension of JavaScript that allows developers to write HTML right within JavaScript. So when you’re writing JSX, technically you’re writing JavaScript and HTML together.

      Also, that means JavaScript’s reserved keywords must be kept intact. And that is why the “for” attribute in HTML is “HTMLFor” in JSX, since «for» is one of the commonest JavaScript reserved keywords.

      In terms of support by browsers, HTML is supported by all of them. JSX, on the other hand, was never really intended to be, so you need a compiler like Babel or Webpack to transpile JSX into the JavaScript that browsers understand.

      The Main Differences Between HTML and JSX

      You need to return a single parent element in JSX

      One of the major differences between HTML and JSX is that in JSX, you must return a single parent element, or it won’t compile.

      A lot of devs use

      .

      , but a better one that many people use is “fragment”, <>. which makes the code more readable.

      In HTML, you are free to do whatever you want as you don’t have to return a single parent element.

      jsx1

      Here you can see that JSX is not compiling because there’s no parent element.

      jsx2

      And here JSX is compiling because there is a parent element (fragment).

      You can implement JS directly in JSX

      In JSX, it is possible to write JavaScript directly. You can do this by putting the JavaScript in curly braces <. >. Whereas in HTML, you need a script tag or an external JavaScript file to implement JavaScript:

      const Article = () => < return ( <> 

      Hi campers

      How's coding going

      What is up?



      is seven in word
      ); >; export default Article;

      All Tags Self-close in JSX

      Tags can self-close in JSX. That is, it is possible to have as and as . You don’t want to do that, but its possible.

      Self-closing tags in HTML can self-close without the slash before the right angle bracket, that is
      could work as
      . But in JSX, you need to include the slash. This should bring something to mind – JSX heavily relies on HTML 4 syntax.

      jsx3

      Here you can see that JSX is not compiling because there’s no forward slash before the right angle bracket of the line break tag.

      jsx4

      And here you can see that JSX is compiling because there is a forward slash in the line break tag.

      ClassName and HTMLFor, not class and for in JSX

      To define class names and for attributes in JSX, you don’t do it as class or for , since both are reserved keywords in JavaScript.

      You actually create class components with the class keyword. So, to define class names in JSX, you do it as » className » and for attributes for labels you write » HTMLFor «:

      const Article = () => < return ( <> 

      Hi campers

      How's coding going

      What is up?



      is seven in word
      ); >; export default Article;

      Write all HTML Attributes in camelCase in JSX

      You need to write all HTML attributes and event references in camelCase while writing JSX. So, onclick becomes onClick , onmouseover becomes onMouseOver , and so on:

      const Article = () => < const sayHI = () =>< alert("Hi Campers"); >; return ( <> 

      Hi campers

      How's coding going

      What is up?



      is seven in word
      ); >; export default Article;

      Write Inline Styles as Objects in JSX

      And lastly, to define inline styles for JSX, you write it as an object, with the properties in camelCase, the values in quotes, and then you pass it inline to the JSX.

      This means you have to open up a style attribute and use curly braces instead of quotes. This is opposed to HTML where you’re free to define millions of styles right inside the opening tag without writing them as objects and putting them in quotes:

      const Article = () => < const inlineStyle = < color: "#2ecc71", fontSize: "26px", >; return ( <> 

      >Hi campers

      How's coding going

      What is up?



      is seven in word
      ); >; export default Article;

      You can choose to write the object directly in the style attribute – that is, by opening up two curly braces and putting the properties and values inside.

      But a cleaner way is to define the object outside of the JSX, and then pass it into the opening tag.

      const Article = () => < return ( <> 

      >>Hi campers

      How's coding going

      What is up?



      is seven in word
      ); >; export default Article;

      Note that you should not use inline styling in plain HTML – you don’t want to ruin your website’s SEO.

      That’s it!

      Thank you for reading. To connect with me, checkout my portfolio, or follow me on Twitter, where I spend most of my time tweeting and engaging in anything web development.

      Источник

      Читайте также:  Simple slider
Оцените статью