LoginSignup
13
9

More than 5 years have passed since last update.

Reactアプリ開発ですぐ使えるJavaScript (ES6) の便利な記法6つ

Last updated at Posted at 2017-08-12

Reactアプリを開発していて便利だと思ったJavaScriptの記法から、特に使い勝手の良いものを6つ紹介してみます。

特にjsxでは記述量の少なさやシンプルさが読みやすさに直結すると思うので、意味が問題なく伝わる範囲でこのようなshorthandをなるべく活用していければと思っています。

これらの書き方が必ずしもベストというわけではなく、好みや開発環境や状況によって他の書き方のほうが良いケースもあると思います。

1. 三項演算子でif文を減らす

ネストさせることも可能。

before

render () {
  const {name} = this.props
  if (!name) {
    return (
      <Message value={'no name'} />
    )
  } else {
    return (
      <User name={name} />
    )
  }
}

after

render () {
  const {name} = this.props
  return name ? <User name={name} /> : <Message value={'no name'} />
}

2. && と || でnullチェックを減らす

null(falsy)チェックや、nullだったときに設定するデフォルト値に使えます。

before


const Name = (props) => {
  const {user} = props
  if (user) {
    return (
      <div>
        {user.name}
      </div>        
    )
  } else {
    return (
      <div>
        {'No User'}
      </div>        
    )
  }
}

after

const Name = (props) => {
  const {user} = props
  return (
    <div>
     {user && user.name || 'No User'}
    </div>
  )
} 

3. map / filter / reduce を使ってfor文を減らす

for構文使う必要がほぼなくなりました。
map / filter / reduceの使い分けについては他の記事を参照してみてください。

before

let jpUsers = []

for (let i = 0; i < users.length; i ++) {
  if (users[i].country === 'jp' ) {
    jpUsers.push(users[i])
  }
}

after

const jpUsers = users.filter(user => user.country === 'jp')

4. アロー関数で'function'を減らす

コールバック関数などがすっきりします。
アロー関数とfunctionは厳密には等価でないようなので、既存のコードを置き換える場合には注意が必要です。

before

function getUserName (user) {
  return user.getName()
}
const userNames = users.map(getUserName)

after

const userNames = users.map(user => user.getName())

5. Objectでproperty名を省略

Objectのproperty名のvalueに入れる変数名が一致する場合、以下のように書くことができます。

before

const name = getName()
const age = getAge()
const userObj = {
  name: name,
  age: age,
  type: 1
}

after

const name = getName()
const age = getAge()
const userObj = {
  name,
  age,
  type: 1
}

6. Spread演算子でObjectを展開

functionの引数にも使えます。

render () {
  const defaultStyle = {
    fontSize: 10,
    fontWeight: 'bold',
    margin: 10
  }
  const blueStyle = {
    ...defaultStyle,
    color: 'blue'
  }
  const textProps = {
    value: 'foo',
    onTouch: this._onTouch,
    style: blueStyle
  }
  return <Text {...textProps} />
}
13
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9