• Stars
    star
    185
  • Rank 207,205 (Top 5 %)
  • Language
  • Created over 7 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React component composition cheatsheet

React component composition cheatsheet

This is a small list of common techniques used in React to compose and enhance components. Feel free to create Pull Requests with further techniques or fixes.

Basic containment

Elements can be passed as children into components.

const Layout = ({ children, theme }) => (
  <div className={`theme-${theme}`}>
    <main>{children}</main>
  </div>
);

const Content = () => (
  <div>Some fancy content</div>
);

ReactDOM.render(
  <Layout theme='dark'>
    <Content />
  </Layout>
, containerEl);

Containment with multiple slots using children

Children are not limited to being elements. You can pass basically anything, including plain objects.

const Layout = ({ children, theme }) => (
  <div className={`theme-${theme}`}>
    <header>{children.header}</header>
    <main>{children.content}</main>
    <footer>{children.footer}</footer>
  </div>
);

const Header = () => (
  <h5>Header title</h5>
);

const Footer = () => (
  <em>footer note</em>
);

const Content = () => (
  <div>Some fancy content</div>
);

ReactDOM.render(
  <Layout theme='dark'>
    {{
      header: <Header />,
      content: <Content />,
      footer: <Footer />
    }}
  </Layout>
, containerEl);

Containment with multiple slots using props

Elements can also be passed in using props.

const Layout = ({ header, content, footer, theme }) => (
  <div className={`theme-${theme}`}>
    <header>{header}</header>
    <main>{content}</main>
    <footer>{footer}</footer>
  </div>
);

const Header = () => (
  <h5>Header title</h5>
);

const Footer = () => (
  <em>footer note</em>
);

const Content = () => (
  <div>Some fancy content</div>
);

ReactDOM.render(
  <Layout
    theme='dark'
    header={<Header />}
    content={<Content />}
    footer={<Footer />}
  />
, containerEl);

Enhancing contained elements

It's possible to enhance certain elements with additional props using React.cloneElement.

const Layout = ({ children, theme }) => (
  <div className={`theme-${theme}`}>
    <main>{React.cloneElement(children, { theme })}</main>
  </div>
);

const Content = ({ theme }) => (
  <div>Currently using this theme: {theme}</div>
);

ReactDOM.render(
  <Layout theme='dark'>
    <Content />
  </Layout>
, containerEl);

Passing components as props

Like elements, you can also pass components in using props.

const Layout = ({ children, contentComponent, theme }) => {
  const ContentComponent = contentComponent;
  return (
    <div className={`theme-${theme}`}>
      <main><ContentComponent theme={theme} /></main>
    </div>
  );
};

const Content = ({ theme }) => (
  <div>Currently using this theme: {theme}</div>
);

ReactDOM.render(
  <Layout
    theme='dark'
    contentComponent={Content}
  />
, containerEl);

Higher Order Components (HOC)

Higher Order Components are functions which get a component passed in as argument and return a new component.

function createComponentWithDefaultProps(WrappedComponent, defaultProps) {
  return (props) => (
      <WrappedComponent {...defaultProps} {...props} />
  );
}

const Layout = ({ children, theme }) => (
  <div className={`theme-${theme}`}>
    <main>{children}</main>
  </div>
);

const DarkLayout = createComponentWithDefaultProps(Layout, { theme: 'dark' });

ReactDOM.render(
  <DarkLayout>Some content</DarkLayout>
, containerEl);

Using functions as children

Since children can be anything, they can also be functions.

class FetchTheme extends React.Component {

  constructor() {
    super();
    this.state = {
      theme: null
    };
  }

  componentDidMount() {
    fetch('/api/currentTheme')
      .then((res) => res.text())
      .then(((theme) => {
        this.setState({ theme });
      }));
  }

  render() {
    const { children } = this.props;
    const { theme } = this.state;
    return theme ? children(theme) : null;
  }
}

const Layout = ({ children, theme }) => (
  <div className={`theme-${theme}`}>
    <main>{children}</main>
  </div>
);

ReactDOM.render(
  <FetchTheme>
  {
    (theme) => (
      <Layout theme={theme}>Some content</Layout>
    )
  }
  </FetchTheme>
, containerEl);

License

Copyright (c) 2017 Simon Kusterer Licensed under the MIT license.

More Repositories

1

castnow

commandline chromecast player
JavaScript
3,810
star
2

dlnacast

Cast local media to your TV through UPnP/DLNA
JavaScript
286
star
3

chromecast-player

simple chromecast player
JavaScript
99
star
4

airtar

send files over the local network using airpaste and tar
JavaScript
91
star
5

limits.js

limits.js helps you to handle API limitations
JavaScript
54
star
6

webcam-binaryjs-demo

Webcam Binary.JS Demo
HTML
32
star
7

torrentcast

raspberry pi torrentcast
JavaScript
27
star
8

chromecast-scanner

scan your local network for chromecast devices and return the first found
JavaScript
27
star
9

Bucket-Balls

Turn your devices into buckets. Impress your friends with "magic" :-)
JavaScript
20
star
10

castv2-youtube

castv2-client youtube sender
JavaScript
20
star
11

finance-stream

realtime stock and exchange stream
JavaScript
15
star
12

hls-chromecast-demo

transcode video and stream it to chromecast on the fly
JavaScript
13
star
13

chromecast-can-play

Check if a certain media file is supported by Chromecast
JavaScript
10
star
14

omxctrl

simple omxplayer wrapper for node
JavaScript
7
star
15

ago

create time templates
JavaScript
6
star
16

lastreturn

get the last return value of a function as argument in the next call
JavaScript
6
star
17

playerui

minimalistic mediaplayer commandline ui
JavaScript
6
star
18

jQuery-DropIt

Lets you drop HTML snippets and images into your html document
JavaScript
5
star
19

lu.js

lightweight dependency injection lib written in JavaScript.
JavaScript
3
star
20

csseval

use expressions to evaluate css on the fly.
JavaScript
3
star
21

co-limits

limits.js version that can be used with co
JavaScript
3
star
22

contao-customselectmenu

Select-Menu with an additional last option 'other value'.
PHP
3
star
23

queryExtend

Like _.extend, just for URL queries.
JavaScript
2
star
24

contao-hooky

Triggering callbacks in Contao made easy
PHP
2
star
25

notify-php

A PHP Class for sending JSON-RPC Notifications
PHP
2
star
26

sope.js

minimalstic javascript boot library
JavaScript
2
star
27

notify-bridge

JSON-RPC notification bridge
JavaScript
2
star
28

contao-rpc

RPC Framework for Contao
PHP
2
star
29

contao-rpc-example

Usage Example for Contao-RPC
PHP
1
star
30

jQuery-bgScroll

Fullscreen Background with up- and down animation
JavaScript
1
star
31

upm-install

atlassian cloud add-on installer
JavaScript
1
star
32

keyval

evented key/value storage lib
JavaScript
1
star
33

understanding-koa

Some koa samples
JavaScript
1
star
34

lambda-compose

lambda-compose adds middleware and promise support to your lambda functions.
JavaScript
1
star
35

node-asin-queue

JavaScript
1
star
36

timeline

another generic timeline module
JavaScript
1
star
37

allow-request

whitelist certain http routes
JavaScript
1
star
38

filteramo

elasticsearch for the poor man
JavaScript
1
star
39

circulate

circulate over an javascript array
JavaScript
1
star
40

jQuery-quoteFade

jQuery plugin which lets you simply loop through a bunch of items with a fade-effect.
JavaScript
1
star
41

fleet

Manage a fleet of Confluence instances with ease
JavaScript
1
star
42

notify-contao

Send push notifications from the contao to the frontend
PHP
1
star