Skip to content

Get wrapped instance #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 2, 2016
Merged

Get wrapped instance #10

merged 3 commits into from
Aug 2, 2016

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