- HTML elements are lowercase (
<div>,<form>), but components are uppercase (<Counter>,<App>). - You can’t just type “class” in JSX; instead, use
className; e.g.,<div className="sidebar">. - To access the realm of JavaScript (and the application state) from within JSX, use curly braces:
{2 + 2 != 5}.
React components and props
The main organizational concept in React is the component. Components are used to contain the functionality for a part of the view within a self-contained package. We’ve seen a component in action already with <App> but it might be a little obscure, so let’s add another simple component to enhance the demonstration. This component also lets us explore another key part of React: Props.
To start, let’s create a display of the counter value influenced by the Rob Reiner movie This Is Spinal Tap. To start, we create a new file at src/VolumeDisplay.jsx:
// src/VolumeDisplay.jsx
export function VolumeDisplay({ level }) {
return (
<div style={{ textAlign: 'center' }}>
{/* The Dial */}
<div style={{
border: '4px solid #333',
borderRadius: '50%',
width: '100px',
height: '100px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '3rem',
margin: '20px auto',
// Dynamic Style: Red if 11
background: level >= 11 ? '#d32f2f' : '#f0f0f0',
color: level >= 11 ? 'white' : 'black',
transition: 'all 0.2s ease'
}}>
{level}
</div>
{/* The Message */}
{level >= 11 && (
<p style={{ color: 'red', fontWeight: 'bold' }}>
"These go to eleven." 🤘
</p>
)}
</div>
);
}
This is a simple display but there are a couple of things worth noting about it.