ARMATAV
ARMATAV

Reputation: 634

Passing data to a component

How exactly should I be passing my data to my components?

var item = {type: 'Friend', content: { emoji: '🍺', name: 'Tom', distance: '0.25mi'}}

Should I try to pass each value with a separate prop?

renderRow(item) {
    return(
        <FriendItem emoji={item.content.emoji} name={item.content.name} distance={item.content.distance} />
    )
}

Or is there a way I can send the whole object through to make my code more modular?

renderRow(item) {
    return(
        <FriendItem item={item} />
    )
}

Upvotes: 0

Views: 61

Answers (2)

Jordan Enev
Jordan Enev

Reputation: 18644

I don't see a reason to pass the props one by one, once you can validate them in the child component.

Here is the shortest syntax:

renderRow(item) {
    return(
        <FriendItem item />
    )
}

For sure I will validate the props in <FriendItem />. Therefore If I'm wondering what props item has to contain, then I can check the required structure in <FriendItem />. Here is how to handle the validation.

Upvotes: 1

Matt Way
Matt Way

Reputation: 33141

Both of your examples are completely valid, and the choice is up to you. To go through them in a little more detail.

  1. Your first example gives you more control over what you expect to be passed to your component. It is more informative to someone using your component, as they can see exactly what is needed. However, on the downside, if you have a lot of props it can become annoying. Also this layout becomes problematic if you have optional props.

  2. This example gives you less control over what you expect (unless you use propTypes, and describe the keys that the object should have - see below), but is much more concise. Personally I prefer this example in your case.

If you use 2, but want to be more informative, use propTypes to explain to the user what is required. See here. An example of what yours might look like:

MyComponent.propTypes = {
  content: React.PropTypes.shape({
    emoji: React.PropTypes.string,
    name: React.PropTypes.string,
    distance: React.PropTypes.number
  })
}

Also, if you do like 1), you can use the spread operator to pass every child key to your prop. This keeps your code short like 2), but provides every prop like 1). Whether or not you use this is up to you, but in your case I would still stick with 2). The spread operator example would look like this (note the spread operator might require extra transpiler plugins):

<FriendItem {...content} />

Upvotes: 1

Related Questions