Let’s create a reusable Card component to show a single user data.

This component will display our image and details as gathered from GitHub. It gets its data via props, using

  • props.avatar_url the user avatar
  • props.name the user name
  • props.blog the user website URL

Let’s make a simple version of it. We style it using the style property of each HTML element. The syntax uses two curly braces, like this:

<div style={{ margin: '1em' }}>

This is because one of the braces pair is to input a JavaScript value in the JSX, like we did for count in the previous project.

The other one is to create an object with the CSS properties:

const Card = props => {
  return (
    <div style={{ margin: '1em' }}>
      <img alt="avatar" style={{ width: '70px' }} src={props.avatar_url} />
      <div>
        <div style={{ fontWeight: 'bold' }}>{props.name}</div>
        <div>{props.blog}</div>
      </div>
    </div>
  )
}

You can check out the official docs for style. This method is a quick way to add CSS without adding classes or a separate CSS file, although we’ll later use those methods as this one is only suited for quick needs or to prototype. In any case, it’s good to know how to use it.

We create a list of those Card components in a CardList component.

A parent component will provide it a list of cards using props, and CardList will take care of iterating over them and render a Card component for each one:

const CardList = props => (
  <div>
    {props.cards.map(card => (
      <Card {...card} />
    ))}
  </div>
)

We use map() to iterate on the array. See my tutorial on it.

Here’s the full code of those 2 first components:

src/components/Card.js:

import React from 'react'

const Card = props => {
  return (
    <div style={{ margin: '1em' }}>
      <img alt="avatar" style={{ width: '70px' }} src={props.avatar_url} />
      <div>
        <div style={{ fontWeight: 'bold' }}>{props.name}</div>
        <div>{props.blog}</div>
      </div>
    </div>
  )
}

export default Card

src/components/CardList.js:

import React from 'react'
import Card from './Card.js'

const CardList = props => (
  <div>
    {props.cards.map(card => (
      <Card {...card} />
    ))}
  </div>
)

export default CardList

Go to the next lesson