skip to Main Content

I’m learning React and I keep on hearing the phrase JSX.

I’ve tried watching videos about it but I still don’t understand what it is.

I’ve also had a look at the documentation but my head is still scrambled I’ve had a look at JSX and to me it just looks like regular HTML.

What is JSX and what is the difference between JSX and HTML?

4

Answers


  1. JSX is what react uses to render content to page. JSX stands for JavaScript as XML, hence it’s HTML like syntax. The extra features of JSX that don’t come with just plain HTML is things like conditional rendering and dynamic content an example of each.

    {showContent ? <p>This is content</p> : null}

    <p>{counter} </p>

    Login or Signup to reply.
  2. JSX is an extension to javascript syntax. It allows writing code that look similar html, and that similarity makes it feel pretty natural in the context of a front end UI library. JSX is very commonly used with React, though technically you could do react without JSX (it would be combersome, so i don’t recommend it), and the JSX syntax can be used with other libraries than react (this isn’t common).

    In the context of react, a JSX element is a shorthand for calling React.createElement. createElement is the code that React uses for describing what should be on the page. For example, the following JSX:

    <div>Hello World</div>
    

    Transpiles to this code:

    React.createElement("div", null, "Hello World");
    

    Which will return an object that looks roughly like this:

    {
      type: 'div',
      props: {
        children: 'Hello World'
      }
    }
    

    That object is then used by React to decide what to do next to update the page to match your intention.

    Login or Signup to reply.
  3. I know my answer is not so tecnical but basically JSX (or TSX if you’re using typescript) is the extension of visual (components) files of your react app. If you try to return any visual component in a JS/TS file you’ll get a lot of syntax errors.

    - my app
      - components
        - myComponent.jsx // this is a component
    

    And inside it you can now return the visual part of your app:

    function MyComponent() {
      const text = 'Hello'
    
     return (
        <div>{ `${ text } world`}</div>
     )
    }
    
    Login or Signup to reply.
  4. JSX basically allows us to write HTML in React as given below:

    function ReactCompoent(){
      return (
        <p>HTML in React <p/>
      )
    }

    It’s called JavaScript XML which is basically a syntax extension for javascript, and in simple words it allows you to write javascript and HTML in a single file together.

    const element = <p>HTML in React <p/>
    

    While JSX looks like HTML, but it’s not HTML. It gets converted (transpiled) into regular JavaScript by tools like Babel before being used in the browser.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search