DEV Community

Cover image for The HTML-JSX fusion
odi pearl
odi pearl

Posted on

The HTML-JSX fusion

INTRODUCTION

JavaScript Extensible Markup Language (JSX) is the fusion point where HTML's structure collides with JavaScript's dynamic capabilities. It's a syntax extension used in React that lets you write HTML-like code within JavaScript, which simplifies the creation of interactive and dynamic user interfaces. Imagine you're building a web page, and you want to describe how things should look and behave. Normally, you'd use HTML for that. JSX is a bit like a cool cousin of HTML that you can use when working with JavaScript, especially in frameworks like React.

With JSX, you can write your webpage structure and UI components in a way that looks a lot like HTML, but you can also include JavaScript inside it.

Integrating HTML into JSX
We will go through a step by step process on integrating HTML into JSX

Step 1
Defining a React Component using JSX:

const MyComponent = () => {
  // ...
};
Enter fullscreen mode Exit fullscreen mode

Defines a functional component named MyComponent using arrow function syntax (() => { ... }).

Step 2
Using JSX within the Component:

const username = 'Pearl';
const greeting = <h1>Hey, {username}!</h1>;

Enter fullscreen mode Exit fullscreen mode
  • Declares a username variable and creates a greeting variable that holds a JSX element.

  • The JSX element <h1>Hello, {username}!</h1> dynamically incorporates the username variable within the greeting.

Step 3
Returning JSX in the Component:

return (
  <div>
    {greeting}
    <p>Welcome to the exciting world of JSX in React!</p>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

The return statement returns JSX, describing the structure of the React component.

The JSX contains a <div> element that nests the greeting variable (which contains the dynamic <h1> element) and a <p> element.

Basically it should look like this...

Image description
.

IMPORTANT FACTS TO NOTE WHEN USING JSX

  • JSX Elements Must Have a Single Root: In JSX, a component's return statement should consist of a single root element. This rule ensures clarity and consistency in the structure of your components. Consider the following example:
// Incorrect: Multiple root elements directly in return
const InvalidComponent = () => {
  return (
    <h1>Hello</h1>
    <p>This is invalid JSX</p>
  );
};
Enter fullscreen mode Exit fullscreen mode

The above code is invalid because there are two sibling elements (<h1> and <p>) directly in the return statement without a common parent.

To resolve this, wrap the elements in a single root element, often a <div>

// Correct: Single root element wrapping multiple elements
const ValidComponent = () => {
  return (
    <div>
      <h1>Hello</h1>
      <p>This is valid JSX</p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
  • JavaScript Expressions Inside Curly Braces: When you write JSX without curly braces, you are essentially treating the content as a plain string or static value. Let's take a simple example:
const GreetingWithoutCurlyBraces = () => {
  const name = "Pearl";

  return <p>Hello, name!</p>;
};
Enter fullscreen mode Exit fullscreen mode

In the above example, the content within the <p> tag is treated as a string literal, not as the variable name. The output would be "Hello, name!" instead of "Hello, Pearl!".

To include dynamic content or JavaScript expressions within JSX, you use curly braces {}. Here's how you would correctly incorporate the name variable

const GreetingWithCurlyBraces = () => {
  const name = "Pearl";

  return <p>Hello, {name}!</p>;
};
Enter fullscreen mode Exit fullscreen mode

Now, with the curly braces around {name}, React interprets it as a JavaScript expression and replaces it with the actual value of the name variable. The output in this case would be "Hello, Pearl!".

  • Inline Styles Use an Object: In JSX, you can apply styles directly to elements using the style attribute. It's important to note that the style attribute doesn't take a string as you might expect in regular HTML. Instead, it takes a JavaScript object where the keys are camelCased style property names, and the values are the corresponding style values:
const StyledComponent = () => {
  const customStyle = {
    color: 'blue',
    fontSize: '16px',
    backgroundColor: 'lightgray',
    padding: '10px'
  };

  return <div style={customStyle}>Styled Content</div>;
};
Enter fullscreen mode Exit fullscreen mode

You can also create dynamic styles based on conditions for example

const DynamicStyleComponent = ({ isHighlighted }) => {
  const dynamicStyle = {
    color: isHighlighted ? 'red' : 'black',
    fontWeight: isHighlighted ? 'bold' : 'normal'
  };

  return <p style={dynamicStyle}>Dynamic Style</p>;
};

Enter fullscreen mode Exit fullscreen mode

In this example, the dynamicStyle object changes based on the isHighlighted prop. If isHighlighted is true, the text color becomes red and the font weight becomes bold; otherwise, it uses the default values.
For more extensive styles or to reuse styles across components, you can define styles outside of the component and import them:

  • Event Handling in JSX:
    Event handlers in JSX are written in camelCase, similar to regular HTML attributes. For example, onClick instead of onclick.

  • Basic Conditional Rendering
    In React, you can conditionally render content by using JavaScript expressions within curly braces. Here's a simple example:

const ConditionalComponent = ({ isLoggedIn }) => {
  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome, User!</p>
      ) : (
        <p>Please log in to access the content.</p>
      )}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In this example, the content within the curly braces {} is evaluated based on the value of the isLoggedIn prop. If isLoggedIn is true, it renders a welcome message; otherwise, it prompts the user to log in.

CONCLUSION

In wrapping up, the fusion of HTML and JSX in React brings about a straightforward and effective way to build dynamic user interfaces. JSX, resembling HTML, integrates seamlessly with JavaScript for added flexibility. It simplifies code structure, promotes reusability through components, and ensures efficient event handling. Compiling JSX to JavaScript ensures browser compatibility, and React's virtual DOM optimization enhances overall performance. This combination forms a solid foundation for crafting modern and responsive web applications.

Top comments (0)