React JSX (JavaScript XML) is a syntax extension for JavaScript recommended by React. It looks similar to XML or HTML and is used to describe what the UI should look like. It converts HTML tags and JavaScript expressions to React elements, which are JavaScript objects representing a part of the UI.
JSX mixes HTML tags and JavaScript expressions. Here’s a simple example:
const element = Hello, World!;
In this example, `element` is a JSX expression representing an `h1` HTML element.
JSX allows embedding any JavaScript expressions within curly braces `{}`:
const name = 'John';
const element = <h1>Hello, {name}!</h1>;
Here, `name` is a JavaScript variable inside the JSX expression.
JSX allows setting HTML attributes using camelCase naming conventions:
const element = <div className="myClass">Hello, World!</div>;
Remember to use `className` instead of `class` as `class` is a reserved keyword in JavaScript.
JSX tags can have child elements or nested elements:
const element = (
<div>
<h1>Hello!</h1>
<p>This is a paragraph.</p>
</div>
);
This example has `div` as a parent element and `h1` and `p` as child elements.
In React, you often define components using JSX. Components can either be function components or class components:
// Function Component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// Class Component
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Both components above are equivalent.
In JSX, tags without children should be self-closed using a slash:
const element = <img src="myImage.jpg" />;
To render a JSX element to the DOM, you use `ReactDOM.render()`:
const element = <h1>Hello, World!</h1>;
ReactDOM.render(element, document.getElementById('root'));
This will render the `h1` element to the DOM element with the ID `root`.
You can use JavaScript logic to conditionally render elements:
function Welcome(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign up.</h1>;
}
Here, `Welcome` will render different content based on `isLoggedIn` prop.
You can build lists by mapping over array elements and assigning a unique `key` prop to each element:
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>{number}</li>
);
ReactDOM.render(
<ul>{listItems}</ul>,
document.getElementById('root')
);
This will render an unordered list with the numbers 1 to 5.
You can handle events such as clicks or user inputs using camelCase event handlers:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
In this example, clicking the link will log a message to the console and prevent the default link behavior.
JSX can be used to render form elements and handle user inputs:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
}
Here, `NameForm` is a controlled component with the form input’s value being controlled by React state.
To return multiple elements from a component, you can use `<React.Fragment>` or the short syntax `<>`:
function Table() {
return (
<React.Fragment>
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
</React.Fragment>
);
}
If you already have `props` as an object and you want to pass it in JSX, you can use `...` as a “spread” operator:
const component = <Component {...props} />;
JSX gets compiled to `React.createElement()` calls, so `<div />` compiles to `React.createElement('div')`. This means that JSX is just syntactic sugar over JavaScript functions and objects.
JSX is an essential part of React and offers a more concise and readable syntax for creating and rendering UI components. It allows for the combination of HTML and JavaScript, enabling developers to describe UIs in a declarative and intuitive way. By understanding the various aspects of JSX, including its syntax, component structure, rendering mechanisms, and conditional rendering, developers can create dynamic, interactive, and modular UIs using React. For instance, let's see a more integrated example using many of the concepts above:
class ToDoApp extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
text: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div>
TODO
<ul>
{this.state.items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
<form onSubmit={this.handleSubmit}>
<label htmlFor="new-todo">
What needs to be done?
</label>
<input
id="new-todo"
onChange={this.handleChange}
value={this.state.text}
/>
<button>
Add #{this.state.items.length + 1}
</button>
</form>
</div>
);
}
handleChange(e
) {
this.setState({ text: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
if (this.state.text.length === 0) {
return;
}
const newItem = {
text: this.state.text,
id: Date.now()
};
this.setState(state => ({
items: state.items.concat(newItem),
text: ''
}));
}
}
ReactDOM.render(
<ToDoApp />,
document.getElementById('todos')
);
In this example, ToDoApp is a React component that represents a to-do application, integrating various aspects of JSX and React concepts like state, event handling, conditional rendering, and lists with keys.
Understanding the examples and concepts above will give you a good start to mastering React JSX. To continue learning, it’s helpful to experiment with building your own components and exploring the official React documentation for more advanced topics and patterns.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here