Introduction to JSX in React

JSX, or JavaScript XML, is a syntax extension for JavaScript used in React to describe the UI structure. It allows developers to write HTML-like code within JavaScript, which gets transformed into React elements. Here’s a brief introduction to JSX:

Syntax:

JSX is a JavaScript syntax extension that looks very similar to XML. Elements are the smallest units that make up a React application, and JSX is used to declare elements in React.

Example:
const element = <h1>Hello, world!</h1>;

Embedding Expressions:

You can embed any JavaScript expression within JSX by using curly braces {}.

Example:

const name = 'John'; const element = <h1>Hello, {name}!</h1>;

Attributes and Children:

JSX allows passing attributes to elements and nesting children elements.

Example:

const element = <div> 
  <h1>hello</h1>
  <h2>world</h2>
</div>;

Styling:

Inline styles in JSX are specified as objects, and the attribute name is style.

Example:

const divStyle = { color: 'blue', backgroundColor: 'lightgray' }; const element = <div style={divStyle}>Styled div</div>;

Class Names:

Use className instead of class to specify CSS classes.

Example:
const element = <div className="container">Hello, world!</div>;

Self-Closing Tags:

For elements without children, you can use self-closing tags.

Example:
const element = <img src="image.png" alt="description" />;

Benefits of JSX

  • Readability: JSX makes it easier to visualize the structure of the UI.
  • Integration: Allows seamless integration of JavaScript with HTML-like syntax.
  • Tooling Support: Enhanced by tools like Babel, which compile JSX into standard JavaScript.

By using JSX, React developers can create more intuitive and maintainable code for their applications.

Exercise in App.js

const divStyle = {
  color: 'blue',
  backgroundColor: 'lightgray'
};

const element = <div style={divStyle}> 
  <h1>hello</h1>
  <h2>world</h2>
</div>;

export default function App() {
  return element;
}
Categories: React

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x