JavaScript di JSX menggunakan Curly Braces
JSX memungkinkan Anda menulis markup mirip HTML di dalam file JavaScript, sehingga membuat logika rendering dan konten berada pada satu tempat yang sama. Terkadang Anda akan ingin menambahkan sedikit logika JavaScript atau merujuk pada properti yang dinamis di dalam markup tersebut. Dalam situasi ini, Anda dapat menggunakan tanda kurung kurawal pada JSX untuk membuka akses ke JavaScript.
You will learn
- Bagaimana cara untuk oper strings dengan tanda kutip
- Bagaimana cara mereferensikan variabel didalam JSX dengan kurung kurawal
- Bagaimana cara memanggil fungsi Javascript didalam JSX dengan kurung kurawal
- Bagaimana cara menggunakan objek Javascript didalam JSX dengan kurung kurawal
Mengoper strings dengan tanda kutip
Ketika Anda ingin oper atribut string ke JSX, Anda memasukkannya ke dalam tanda kutip tunggal atau ganda:
export default function Avatar() { return ( <img className="avatar" src="https://i.imgur.com/7vQD0fPs.jpg" alt="Gregorio Y. Zara" /> ); }
Disini, "https://i.imgur.com/7vQD0fPs.jpg"
dan "Gregorio Y. Zara"
sedang dioper sebagai strings.
Namun bagaimana jika Anda ingin secara dinamis menentukan teks src
atau alt? Anda dapat **menggunakan nilai dari JavaScript dengan mengganti
”dan
”dengan
dan `**:
export default function Avatar() { const avatar = 'https://i.imgur.com/7vQD0fPs.jpg'; const description = 'Gregorio Y. Zara'; return ( <img className="avatar" src={avatar} alt={description} /> ); }
Perhatikan perbedaan antara className="avatar"
, yang menentukan nama kelas CSS "avatar"
yang membuat gambar bulat, dan src={avatar}
yang membaca nilai variabel JavaScript disebut avatar
. Hal itu terjadi karena kurung kurawal memungkinkan Anda bekerja dengan JavaScript langsung di markup Anda!
Menggunakan kurung kurawal: Jendela ke dunia JavaScript
JSX merupakan cara khusus dalam menulis JavaScript. Artinya, memungkinkan untuk menggunakan JavaScript di dalamnya - dengan kurung kurawal { }
. Contohnya di bawah ini pertama-tama mendeklarasikan sebuah nama untuk ilmuwan, name
, kemudian menyematkannya dengan kurung kurawal di dalam <h1>
:
export default function TodoList() { const name = 'Gregorio Y. Zara'; return ( <h1>{name}'s To Do List</h1> ); }
Coba ubah nilai name
dari 'Gregorio Y. Zara'
menjadi 'Hedy Lamarr'
. Lihat bagaimana judul daftar berubah?
Any JavaScript expression will work between curly braces, including function calls like formatDate()
:
const today = new Date(); function formatDate(date) { return new Intl.DateTimeFormat( 'en-US', { weekday: 'long' } ).format(date); } export default function TodoList() { return ( <h1>To Do List for {formatDate(today)}</h1> ); }
Where to use curly braces
You can only use curly braces in two ways inside JSX:
- As text directly inside a JSX tag:
<h1>{name}'s To Do List</h1>
works, but<{tag}>Gregorio Y. Zara's To Do List</{tag}>
will not. - As attributes immediately following the
=
sign:src={avatar}
will read theavatar
variable, butsrc="{avatar}"
will pass the string"{avatar}"
.
Using “double curlies”: CSS and other objects in JSX
In addition to strings, numbers, and other JavaScript expressions, you can even pass objects in JSX. Objects are also denoted with curly braces, like { name: "Hedy Lamarr", inventions: 5 }
. Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces: person={{ name: "Hedy Lamarr", inventions: 5 }}
.
You may see this with inline CSS styles in JSX. React does not require you to use inline styles (CSS classes work great for most cases). But when you need an inline style, you pass an object to the style
attribute:
export default function TodoList() { return ( <ul style={{ backgroundColor: 'black', color: 'pink' }}> <li>Improve the videophone</li> <li>Prepare aeronautics lectures</li> <li>Work on the alcohol-fuelled engine</li> </ul> ); }
Try changing the values of backgroundColor
and color
.
You can really see the JavaScript object inside the curly braces when you write it like this:
<ul style={
{
backgroundColor: 'black',
color: 'pink'
}
}>
The next time you see {{
and }}
in JSX, know that it’s nothing more than an object inside the JSX curlies!
More fun with JavaScript objects and curly braces
You can move several expressions into one object, and reference them in your JSX inside curly braces:
const person = { name: 'Gregorio Y. Zara', theme: { backgroundColor: 'black', color: 'pink' } }; export default function TodoList() { return ( <div style={person.theme}> <h1>{person.name}'s Todos</h1> <img className="avatar" src="https://i.imgur.com/7vQD0fPs.jpg" alt="Gregorio Y. Zara" /> <ul> <li>Improve the videophone</li> <li>Prepare aeronautics lectures</li> <li>Work on the alcohol-fuelled engine</li> </ul> </div> ); }
In this example, the person
JavaScript object contains a name
string and a theme
object:
const person = {
name: 'Gregorio Y. Zara',
theme: {
backgroundColor: 'black',
color: 'pink'
}
};
The component can use these values from person
like so:
<div style={person.theme}>
<h1>{person.name}'s Todos</h1>
JSX is very minimal as a templating language because it lets you organize data and logic using JavaScript.
Recap
Now you know almost everything about JSX:
- JSX attributes inside quotes are passed as strings.
- Curly braces let you bring JavaScript logic and variables into your markup.
- They work inside the JSX tag content or immediately after
=
in attributes. {{
and}}
is not special syntax: it’s a JavaScript object tucked inside JSX curly braces.
Challenge 1 of 3: Fix the mistake
This code crashes with an error saying Objects are not valid as a React child
:
const person = { name: 'Gregorio Y. Zara', theme: { backgroundColor: 'black', color: 'pink' } }; export default function TodoList() { return ( <div style={person.theme}> <h1>{person}'s Todos</h1> <img className="avatar" src="https://i.imgur.com/7vQD0fPs.jpg" alt="Gregorio Y. Zara" /> <ul> <li>Improve the videophone</li> <li>Prepare aeronautics lectures</li> <li>Work on the alcohol-fuelled engine</li> </ul> </div> ); }
Can you find the problem?