Skip to content

Instantly share code, notes, and snippets.

@captbaritone
Created September 2, 2016 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save captbaritone/06c4a99700d8f5b3234a3e309a5b1ad8 to your computer and use it in GitHub Desktop.
Save captbaritone/06c4a99700d8f5b3234a3e309a5b1ad8 to your computer and use it in GitHub Desktop.

React Component

The heart of a Hearsay component is a React component. The props (state) passed into the React component can be completely decoupled from

propTypes

Since components are used in many projects, it's very useful to have them explicitly define the "contract" that they implement. IE, what inputs they expect. Combining this information with our fixture data, we can have our automated tests check that each project that uses this component is passing it data that is more-or-less correct.

Additionally, this information can be used as documentation, explaining to anyone attempting to use the component. If we needed, we could even programmatically convert these definitions into human readable docs

Any property that your component uses must be documented with an appropriate propType on the component that your index.jsx file exports. Having the propTypes documented at the top level gives users of the component a single obvious place to learn what the component requires. You can learn more about React propTypes here: https://facebook.github.io/react/docs/reusable-components.html#prop-validation

Writing your render function

When writing your render function, try to keep all JSX in one block rather than assigning small blocks to variables and then interpolating those variables. This allows other engineers to easily see the structure of the HTML that the component will generate. If you find your JSX is getting too deeply nested, abstract blocks into helper components.

There are a few idioms that allow you to leverage JavaScript boolean operators to keep conditional blocks inline:

If (and)

render() {
    return <div>
        {this.props.link &&
            <a href={this.props.link.url}>Click Here</a>
        }
    </div>;
}

If/Else (ternary)

render() {
    return <div>
        {this.props.loading ?
            <img src='spinner.gif' />
        :
            <div>Done loading!</div>
        }
    </div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment