banner
小凯同学 xkfe

小凯同学 xkfe

学而不思则罔,思而不学则殆
twitter
github
email

Usage of Common JSX Syntax

What is JSX?#

JSX is a syntax extension for JavaScript that allows you to write HTML code within JavaScript. It was introduced in 2013 alongside the release of the React library and simplifies the development process of user interfaces while improving code readability and maintainability.

For example🌰

// React code without JSX
const element = React.createElement('h1', { className: 'title' }, 'Hello, world!');

// React code with JSX
const element = <h1 className="title">Hello, world!</h1>;

Tip

JSX is stricter than HTML. You must close tags, such as <br />. Your components cannot return multiple JSX tags; you must wrap them in a single parent, like <div>...</div> or use empty <>...</>:

function Hello() {
  return (
    <>
      <h1>Hello, world!</h1>
    </>
  );
}

Embedding Expressions in JSX#

const name = 'John Doe';
const fn = () => alert('fn function');

const App = () => {
  return (
    <>
      <h1>{ name }</h1>
      <button>{ fn() }</button>
      <p>{ new Date().toLocaleString() }</p>
    </>
  );
};

Adding Attributes in JSX#

Warning

Since JSX is closer to JavaScript than HTML, React DOM uses camelCase property naming conventions instead of HTML attribute names.
For example, class becomes className in JSX, and tabindex becomes tabIndex.

const user = {
  className: 'avatar-img',
  imageUrl: 'https://www.gravatar.com/avatar/0?d=mp',
  style: {
    border: '2px solid red',
    borderRadius: '50%',
  }
}

const App = () => {
  return (
    <>
      <img src={ user.imageUrl } className={ user.className } style={user.style} alt="Avatar" />
    </>
  );
};

Binding Events in JSX#

Use tsx to bind events with on[Click]{ fn } in camelCase. The same applies to other events. If you need to pass parameters, you can use on[Click]{ () => fn() }.

const clickFn = (name) => {
  console.log('clicked', name);
}
const mouseEnterFn = () => {
  console.log('mouse entered');
}
const mouseLeaveFn = () => {
  console.log('mouse left');
}

const App = () => {
  return (
    <>
      <h1>Hello, world!</h1>
      <button onClick={() => clickFn('button')} onMouseEnter={mouseEnterFn} onMouseLeave={mouseLeaveFn}>Click me</button>
    </>
  );
};

Conditional Rendering in JSX#

const flag = true;

const App = () => {
  return (
    <>
      <div>{ flag ? <div>True</div> : <div>False</div> }</div>
    </>
  );
};

When you don't need an else branch, you can also use the shorter logical && syntax:

<div>
  {isLoggedIn && <AdminPanel />}
</div>

More complex conditional logic can be written in a function:

const messageTip = (code) => {
  switch (code) {
    case 200:
      return <div className="message-tip success">Success</div>;
    case 404:
      return <div className="message-tip error">Error</div>;
    default:
      return <div className="message-tip info">Info</div>;
  }
}
const App = () => {
  return (
    <>
      { messageTip(200) }
    </>
  );
};

Iterating Elements in JSX#

Use map to iterate and return HTML tags:

const userList = [
  { id: 1, name: 'John Doe', age: 18, gender: 'Male' },
  { id: 2, name: 'Jane Smith', age: 19, gender: 'Female' },
  { id: 3, name: 'Mike Johnson', age: 20, gender: 'Male' },
  { id: 4, name: 'Emily Davis', age: 21, gender: 'Female' },
  { id: 5, name: 'Chris Brown', age: 22, gender: 'Male' },
  { id: 6, name: 'Sarah Wilson', age: 23, gender: 'Female' },
  { id: 7, name: 'David Lee', age: 24, gender: 'Male'},
]
const App = () => {
  return (
    <>
      { userList.filter(user => user.age > 20).map(user => <div key={user.id}>{user.name}</div>) }
    </>
  );
};

Rendering HTML Fragments in JSX#

Warning

After using dangerouslySetInnerHTML, do not add content to the element, or it will cause an error.

const App = () => {
  return (
    <>
      <div dangerouslySetInnerHTML={{__html: el}}>{/* Leave this empty, or it will throw an error */}</div>
    </>
  );
};

Common Issues#

1. Only expressions can be used within JSX statements; statements and literals cannot be used.

// Error: Objects are not valid as a React child (found: object with keys {key}). If you meant to render a collection of children, use an array instead.
const element = <div>{ { key: 'value' } }</div>;

// ✅
const element = <div>{ JSON.stringify({ key: 'value' }) }</div>;

// ✅
const element = <div>{ { key: 'value' }.key }</div>;

2. How to use generics in TSX
Writing generic syntax normally conflicts with tsx syntax, as it interprets generics as an element. The solution is to add a , at the end.

const clickTap = <T,>(params: T) => alert(params);
const element = <button onClick={() => clickTap('John Doe')}>Click me</button>;
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.