I'm making my first large React-based personal project, and I caught myself putting too many plain old function calls in my JSX, stuff where I might have a function like
const renderRowLabels = (soundSet, keyCurrentlyPressed) => {
being called by code in (in JSX) like
{renderRowLabels(soundSet, keyCurrentlyPressed)}
it's more idiomatic in React to make such DOM-element corresponding things look more like a tag... so the function becomes
const RowLabels = ({soundSet, keyCurrentlyPressed}) => {
since those two arguments will be passed as keys inside a props object, but we can destructure them on the fly so we don't have to refactor any code below.
Then we change the call to something like
<RowLabels soundSet={soundSet} keyCurrentlyPressed={keyCurrentlyPressed} />
But that's a little ugly, right? Redundant. With ECMAScript hotness, we can take advantage of how we are using the same names for variables in both places, and packup a nice properties bit again with the ... operator:
<RowLabels {...{ soundSet, keyCurrentlyPressed }} />
A little weird looking the first time you see it, but more true to how React sort of wants to be written...
(Note this assumes you are using the same variables names in the parent and the child. Otherwise feel free to mashup this use of the spread operator with regular properties, like
<RowLabels {...{ soundSet}} key={keyCurrentlyPressed} />)
I remember a few months ago when I first "got" the spread operator - how it feels like letting things bust out from serial to parallel, somehow...
No comments:
Post a Comment