Step 13
Let's refactor the Phonetics.js
as follows.
function Phonetics() {
const phonetics = [
{
text: "/həˈloʊ/",
audio: "https://lex-audio.useremarkable.com/mp3/hello_us_1_rr.mp3",
},
{
text: "/hɛˈloʊ/",
audio: "https://lex-audio.useremarkable.com/mp3/hello_us_2_rr.mp3",
}
];
return (
<section className="section is-medium pt-0 pb-6" id="phonetics">
<h1 className="title">Phonetics</h1>
{
phonetics.map((phonetic, index) => {
return (
<article className="message is-medium" key={index}>
<div className="message-header">
{phonetic.text}
</div>
<div className="message-body">
<audio controls style={{width: "100%"}}>
<source src={phonetic.audio} type="audio/mpeg"/>
Your browser does not support the audio element.
</audio>
</div>
</article>
)
})
}
</section>
);
}
export default Phonetics;
Notice the data (phonetics
array) is separated from the layout (UI). We create the <article>
element for each entry in the phonetic
array using the map
function.
The return value of the Phonetics
might seem strange to you as we embed JavaScript inside HTML. This is because React's creators designed a syntax extension to JavaScript, called JSX, that allows us to mix JavaScript with HTML. When we combine JavaScript with HTML in JSX, we must put the JavaScript bits in {}
.
There is a lot that can be done with JSX. There are some gotchas and nuances too! For example, we must change HTML class
attribute to className
. Moreover, note how the style
attribute receives an object as in style={{width: "100%"}}
. Finally, notice the key={index}
attribute of the <article>
element. The "key" is not a standard HTML attribute! Delete it, then save the file, and open the Developer Tool in the browser. Notice a warning printed to the terminal
The warning says each HTML element returned by the map function must have a unique key. The key helps React track changes in the child elements as the state changes in the app. Put the "key" attribute back where it was and save the file! Then, the warning should go away.
JSX may feel strange, and you may be confused when first starting using it. In my experience, though, you will quickly get the hang of it, and then it will increase your coding productivity.