Skip to content

Conversation

@javivelasco
Copy link
Owner

This PR adds a new method for the decorator component that allows to retrieve a reference from the decorated component. This is useful for use cases where the component has imperative methods that can be called from a parent.

The most straightforward case is an Input component. Since the focus state is implemented in the native input, to remove the focus it's a common pattern to retrieve the DOM element instance using a ref of findDOMNode and to call blur() over the given element. This way, an Input component that is rendering a native input would typically have both blur and focus methods.

Decorating this kind of component doesn't allow to access the ref to call instance methods so we followed the same pattern as react-redux. Since functional components cannot hold refs, you can pass from now on a new parameter withRef to indicate if the wrapper should render with a reference. Then you can use getWrappedInstance to get the instance.

Example:

import React, { Component } from 'react'
import { themr } from 'react-css-themr'
import Input from './Input.js'
import theme from 'theme.css'

const ThemedInput = themr('MyThemedInput', theme, { withRef: true })

class BlurMyInput extends Component {
  handleClick = () => {
    this._input.getWrappedInstance().focus();
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click me to focus input</button>
        <ThemedInput ref={c => this._input = c} />
      </div>
    )
  }  
}

@javivelasco javivelasco merged commit eebd3dd into master Aug 2, 2016
@javivelasco javivelasco deleted the get-wrapper-instance branch August 2, 2016 19:20
@javivelasco javivelasco changed the title Get wrapper instance Get wrapped instance Aug 3, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant