Embed JavaScript Expressions in JSX
Using JavaScript Expressions in JSX
JSX will only accept expressions between curly braces. The curly braces tell our transpiler to process what is between the curly braces as normal JavaScript. Note we cannot write full statements as we might expect, only bits of JavaScript that return a value. Here are a few common types of expressions you may use:
- Variable and object values
- Function calls and references
- Expressions and operators
- Loops and iteration
Example 1
import React from "react";
const price = 2000;
export default function Vehicles() {
return(
<div>
Car Price: {price}
</div>
);
}
Example 2
import React from "react";
const price = 2000;
const tax = price * 0.10;
export default function Vehicles() {
return(
<div>
Car Price: {price + tax}
</div>
);
}
Example 3
import React from "react";
const car = "MG Hector";
const specifications = {
length : 4655,
width : 1835,
height : 1760
}
const getDimensions = specifications => (
`${specifications.length}(mm) ${specifications.width}(mm) ${specifications.height}(mm)`
);
export default function Vehicles() {
return(
<div>
<p>{car}</p>
<p>{getDimensions(specifications)}</p>
</div>
);
}
Example 4
import React from "react";
const price = 8000;
export default function Vehicles() {
if (price < 5000) {
return <div>Car Price: {price + (price * 0.05)}</div>
} else {
return <div>Car Price: {price + (price * 0.15)}</div>
}
}
Example 5
import React from "react";
const cars = ["MG Hector", "Hyundai Venue", "Toyota Fortuner",
"Hyundai Creta"];
const carList = cars.map((car) =>
<li key={car.toString()}>{car}</li>
);
export default function Vehicles() {
return <ul>{carList}</ul>
}
Using Events in JSX
Expressions are used to tell React how to respond to events when they are triggered by an element. A list of li returned by the Vehicles component and used the onClick prop to tell React how to respond when the click event is triggered.
import React, { Component } from "react";
class Vehicles extends Component {
constructor(props) {
super(props)
this.list_element = React.createRef()
this.state = {
items: [
{ text: 'MG Hector'},
{ text: 'Hyundai Venue'},
{ text: 'Toyota Fortuner'},
{ text: 'Hyundai Creta'}
]
}
}
doSomething(text, index) {
alert(text);
}
render() {
return (
<ol>
{this.state.items.map((item, index) => (
<li key={item.text} onClick={() => this.doSomething(item.text, index)}>
<span>{item.text}</span>
</li>
))}
</ol>
);
}
}
export default Vehicles;