While building a meme generator with React (following freeCodeCamp), I hit a moment where my mental model of JavaScript syntax completely betrayed me — and untangling it taught me something I won't forget.
I was building a controlled component: two text inputs (top text, bottom text) that update state as the user types. Here's the handler:
function handleChange(event) {
const { value, name } = event.currentTarget
setMemeText(prevMeme => ({
...prevMeme,
[name]: value
}))
}
That [name]: value line stopped me cold. In my head, square brackets meant one thing: arrays. So my brain tried to read this as some kind of array operation happening inside an object spread, and none of it made sense.
What was actually going on
[name] is a computed property name. name is a variable holding a string — in this case, either "topText" or "bottomText" (pulled from the input's name attribute). Wrapping it in square brackets tells JavaScript: "don't use the literal word name as the key — evaluate this variable and use its value as the key instead."
Without the brackets, { ...prevMeme, name: value } would spread the previous state and then literally add a property called name set to whatever was typed. That's not what I wanted — I wanted the actual key to be topText or bottomText, depending on which input fired the event. The brackets are the difference between "the key is the word name" and "the key is whatever name currently equals."
One line, one small syntax convention, and suddenly one function could handle both inputs instead of writing a separate handler for each.
Full context — the input side
<input
type="text"
name="topText"
onChange={handleChange}
value={memeText.topText}
/>
The name="topText" on the JSX element is what flows into event.currentTarget.name — which is then the value that [name] computes from. Once I traced that full loop — JSX attribute → event object → destructured variable → computed key — it clicked.
Takeaway
If square brackets in an object literal ever throw you off, ask whether you're looking at a computed property name rather than an array. It's a small piece of syntax that does a lot of quiet work.
Still working through the freeCodeCamp React course — challenge sections left before I move on to real project builds.
Top comments (0)