iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍡

Simplifying JSX Props: Using Spread Syntax to Write <Foo a={a} b={b}> as <Foo {...{a, b}}>

に公開2件

Introduction

Usually, when passing parameters in JSX, it looks like this:

<Foo a={a} b={b} />

However, as the number of parameters increases or when you need to pass them around, it can become quite tedious:

<Foo a={a} b={b} c={c} d={d} e={e} />

Using the Spread Operator

First, these can be passed as a spread operator by grouping them into a single value. If you are just passing them through from parent to child, it looks like this:

const Baz = (props) => {
  return <Foo {...props}>
}

If you want to destructure them and use them elsewhere as well, it might look like this:

const Baz = (props) => {
  const {a, b, c} = props
  return <>
    <div>{a}</div>
    <Foo {...props} />
    <Bar b={b} />
  </>
}

Or something like this:

const Baz = ({a, b, c}) => {
  const props = {a, b, c} 
  return <>
    <div>{a}</div>
    <Foo {...props} />
    <Bar b={b} />
  </>
}

However, there might be cases where you are doing slightly redundant re-assignments or passing unnecessary values.

Main Topic

Combining the Spread Operator with Shorthand Property Names

I mentioned above:

const props = {a, b, c} 

This is what's called Shorthand property names.

By combining this with the spread operator as {...{a, b, c}}, you can write it like this:

const Baz = ({a, b, c}) => {
  return <>
    <div>{a}</div>
    <Foo {...{a, b, c}} />
    <Bar b={b} />
  </>
}

Advantage 1: You can omit braces

With this style, you can omit the braces (of the arrow function). This is nice.

const Baz = ({a, b, c}) => (<>
    <div>{a}</div>
    <Foo {...{a, b, c}} />
    <Bar b={b} />
  </>
)

Advantage 2: No need to pass unnecessary properties

When grouping things like props = { a, b, c }, I sometimes found it inconvenient because I ended up passing parameters that weren't really needed. This writing style allows you to eliminate that problem effectively.

const Baz = ({a, b, c}) => (
  <>
    <NeedAandB {...{a, b}} />
    <NeedBandC {...{b, c}} />
  </>
)

Advantage 3: Renaming is easy

Even if you need to change the name of some properties, it is easy to handle.

const Baz = ({a, b, c}) => (
  <>
    <NeedAandB {...{apple: a, banana: b, c}} />
    <NeedBandC {...{b, c}} />
  </>
)

Discussion

クロパンダクロパンダ

この方法、余計なプロパティを渡せてしまうので不意の事故につながりそうで若干怖いなと思ってます(おそらくそんなに問題にならないと思いますが)

2
terrierscriptterrierscript

その点はspread演算子全般に共通する話だと思いますが、外部ライブラリ等では使わないようにするなどの心遣いをしても良いかもしれませんね。

1