What is JSX?
What is JSX?
JSX, which stands for JavaScript XML, is a syntax extension for JavaScript that allows developers to write HTML-like code within JavaScript files. It was developed by Facebook (now Meta) and is primarily used with the React library to build user interfaces.
HTML-like Syntax: JSX allows developers to write code that looks similar to HTML, making it easier to create and visualize the structure of the UI components. For example:
const element = <h1>Hello, world!</h1>;
This code snippet looks like HTML but is actually JavaScript.
Transpilation: Browsers do not understand JSX directly. Therefore, JSX code needs to be transpiled into regular JavaScript using tools like Babel. For instance, the above JSX code is transformed into:
const element = React.createElement('h1', null, 'Hello, world!');
This transformation allows the browser to execute the code[2][5][13].
Integration with JavaScript: JSX allows embedding JavaScript expressions within curly braces {}
. This feature enables dynamic content rendering based on JavaScript logic. For example:
const name = "John";
const element = <h1>Hello, {name}!</h1>;
This will render as <h1>Hello, John!</h1>
[1][4][9].
Attributes and Props: JSX supports attributes similar to HTML, but with some differences. For example, the class
attribute in HTML is written as className
in JSX to avoid conflicts with JavaScript reserved keywords. Additionally, custom attributes can be passed as props to components[1][4][9].
Conditional Rendering: JSX does not support if-else statements directly within the markup. Instead, it uses conditional expressions or ternary operators. For example:
const isLoggedIn = true;
const element = <h1>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</h1>;
This will render either "Welcome back!" or "Please sign in." based on the value of isLoggedIn
[1][9][13]....
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào