ReasonJun

React : Basic Rules for JSX 본문

Frontend/React

React : Basic Rules for JSX

ReasonJun 2023. 6. 11. 01:07
728x90

Babel is a tool that extands the grammar of JavaScript. It converts the latest, convenient, or experimental JavaScript grammar that is not yet supported into a formal JavaScript format, allowing it to run properly even in an older browser-like environment. For JSX to properly convert to JavaScript, there are several rules you must follow.

  • At least two tags must be wrapped in one tag or use 'Fragment'.
import React from 'react';

const MyComponent = () => {
  const name = 'John Doe';

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>This is a JSX component.</p>
      <button onClick={() => console.log('Button clicked.')}>Click me</button>
    </div>
  );
};

export default MyComponent;

If you want to create multiple elements in JSX, you need to wrap them with opening and closing tags at the top.

 

  • When you need to show JavaScript variables inside JSX, wrap them around {}.

  • The way JSX sets style and CSS class for tags is different from how HTML sets them.

First of all, inline styles should be created in the form of objects, and names separated by - like 'background-color' should be named in the form of camelCase like 'backgroundColor'.

  • Also, when setting CSS class, you must set it to className = , not class=.

  • Basic usage of props

Suppose you want to pass the value 'name' when using the Hello component in the App component. Then, you can write the code like this.

Now, let's find out what to do when you want to use the name value in the Hello component.

  • Multiple props, unstructured assignments.

  • Custom components must start with an uppercase letter.

  • The ternary operator is used for conditional rendering.

  • To display multiple HTML elements in React, use the "map()" function.

When using the map function, you must include the "key" JSX attribute.

If you don't put the "key" JSX attribute, you'll get a warning that you must put a key in each item in the list.

728x90
Comments