Writing Markup with JSX in React

JSX is an extension to JavaScript that allows you to write XML-like code to create and manipulate React elements. With JSX, you can easily define dynamic content and manipulate the DOM elements. In this article, we will discuss how to write markup with JSX in React.

Basic Syntax for JSX JSX syntax is compiled directly into JavaScript functions. The syntax uses a combination of curly braces and tag names to create dynamic markup. Here is a basic example of how to use JSX in a React component:

import React from "react";

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome back, user!</p>
      ) : (
        <p>Please sign up or sign in</p>
      )}
    </div>
  );
}

export default Greeting;

In the code above, we import the React library and define a functional component called Greeting. We then use the JSX syntax to create dynamic content within our HTML render function. The curly braces allow us to include JavaScript expressions and functions within our markup.

Use of Default Function in JSX We can also use the default function with JSX syntax, which allows us to return the HTML tag inside of a function, as shown in the below code:

default function Bio() {
  return (
    <div>
      <div className="intro">
        <h1>Welcome to my website!</h1>
      </div>
      <p className="summary">
        You can find my thoughts here.
        <br /><br />
        <b>And <i>pictures</i></b> of scientists!
      </p>
    </div>
  );
}

CSS in JSX JSX also allows you to use CSS syntax within your components. You can use the style attribute to add inline styles, or define CSS classes and use them with the className attribute. Here is an example:

const person = {
  name: 'Gregorio Y. Zara',
  imageId: '7vQD0fP',
  imageSize: 's',
  theme: {
    backgroundColor: 'black',
    color: 'pink'
  }
};

function TodoList() {
  return (
    <div style={person.theme}>
      <h1>{person.name}'s Todos</h1>
      <img
        className="avatar"
        src={'https://i.imgur.com/' + person.imageId + person.imageSize + '.jpg'}
        alt={person.name}
      />
      <ul>
        <li>Improve the videophone</li>
        <li>Prepare aeronautics lectures</li>
        <li>Work on the alcohol-fuelled engine</li>
      </ul>
    </div>
  );
}

In the above code, we define an object called person with a theme attribute that defines the background color and text color. We use the style attribute to apply this theme to our main component div. We also define a CSS class called .avatar and apply it to our img tag using the className attribute.

In conclusion, writing markup with JSX in React is a powerful way to create dynamic content and manipulate the DOM elements. With JSX, you can easily define HTML tags and CSS classes within your JavaScript code. Understanding how to use JSX syntax and how to apply CSS in JSX will help you create more powerful React components.