Skip to content

Instantly share code, notes, and snippets.

@jonidelv
Created April 13, 2018 11:59
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 jonidelv/c1a4b3ed5ae5c81ab0b3285e1360f226 to your computer and use it in GitHub Desktop.
Save jonidelv/c1a4b3ed5ae5c81ab0b3285e1360f226 to your computer and use it in GitHub Desktop.

React patterns

Higher Order Components vs. Render props

Higher Order Components (HOCs)

Una funcion que recibe un componente y devuelve otro, agregandole cierto comportamiento.

Ejemplo

Edit HOCs

Uso

import React from 'react'

import withMouse from './withMouse'

const App = ({ x, y }) => (
  <div style={{ height: '100vh' }}>
    The mouse position is ({x}, {y})!
  </div>
)

export default withMouse(App)

Implementacion

import React from 'react'
import hoistStatics from 'hoist-non-react-statics'

import { getName } from './utils'

const withMouse = Component => {
  class WrappedComponent extends React.Component {
    static displayName = `withMouse(${getName(Component)})`

    state = {
      x: 0,
      y: 0
    }

    handleMouseMove = event => {
      this.setState({
        x: event.clientX,
        y: event.clientY
      })
    }

    render() {
      return (
        <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
          <Component {...this.props} {...this.state} />
        </div>
      )
    }
  }

  return hoistStatics(WrappedComponent, Component)
}

export default withMouse

Render props (or funciton as a child)

Componentes que delegan el renderizado al cosumidor aceptando una funcion como prop (lo mas usado es children o render) y renderizan el resultado de llamar esa funcion con ciertos parametros.

Recursos

Ejemplo

Edit render-props

Uso

import React from 'react'

import Mouse from './Mouse'

const App = () => (
  <Mouse>
    {({ x, y }) => (
      <div style={{ height: '100vh' }}>
        The mouse position is ({x}, {y})!
      </div>
    )}
  </Mouse>
)

export default App

Implementacion

import React from 'react'

class Mouse extends React.Component {
  state = {
    x: 0,
    y: 0
  }

  handleMouseMove = event => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    })
  }

  render() {
    const rcb = this.props.children || this.props.render

    return (
      <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
        {rcb(this.state)}
      </div>
    )
  }
}

export default Mouse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment