There are several ways to write JavaScript with HTML. But JSX reduces the complexity of writing HTML in mixture with JavaScript.

The Vanilla JavaScript way

"<p>"+somevar+"</p>

The ES6 way

`<p>${variable}</p>`

In react, there’s a thing called JSX, which allows us to mix JavaScript and HTML. It’s also referenced to as syntax extension to JavaScript.

The JSX way

const someVar = 'Devpeel';
<p>hello from {someVar}</p>

Highlighting most common Issues that occur with JSX

Multiple Siblings

You might sometime run into a situation, where you’ve tried to use multiple HTML elements inside your render method and JSX throws you an error that Adjacent JSX Elements must be wrapped in an enclosing tag.

There are couple of solutions to this. Either you can wrap your HTML with <React.Fragment></ReactFragment> tags or with newer react versions, you can use empty tags, likeso <></>

render() {
    return (
        <>
            <p>Sign up please!</p>
            <form className="register-form">
                <h1>Register Form</h1>
            </form>
        </>
    )
}

Commenting

In JSX, you write comments like {/* my comment */}. Most common problem occur if you try to place your comment besides your elements. Remember, comment MUST be inside of your element. As in JSX, you cannot return both the comment and element.

render() {
    return (
        <>
            <p>Sign up please!</p>
            <form className="register-form">
                {/* this is some comment */}
                <h1>Register Form</h1>
            </form>
        </>
    )
}

You may also Like