Search code examples
reactjsreact-reduxredux-formstyled-components

innerRef to third party component


I'm using Redux Form together with Styled Components.

I would like to get the ref of a Redux Form Field, so I can focus it in certain conditions.

The code looks something like: (a little bit simplified)

export const SomeForm = () => (
  <form onSubmit={handleSubmit} >
    <FormLabel htmlFor="comment">Comment:</FormLabel>
    <CommentTextArea
      name="comment"
      component="textArea"
      maxLength="250"
      innerRef={commentBox => this.commentBox = commentBox}
    />
  </form>
);

Where the CommentTextArea is a styled component like such:

const CommentTextArea = styled(Field)`
  background-color: grey;
  border-radius: 3px;
  color: black;
  height: 6.5rem;
  margin-bottom: 1rem;
`;

The problem is that the innerRef's this value is undefined. Is there a way to get access to the ref of the textArea and focus it when necessary?

(FormLabel is also a styled component, but not necessary to show it for the problem)

Thanks in advance.


Solution

  • Wow! I wrote redux-form and I adore styled-components, but it never occurred to me to do styled(Field). That's pretty wild, as I don't consider Field to be a "rendering component" that can be "styled".

    However, I think the puzzle piece you are missing is that you need to pass a withRef prop to Field, which will then enable you to use getRenderedComponent() to get the actual textarea component. Something like:

    <CommentTextArea
      name="comment"
      component="textArea"
      maxLength="250"
      withRef
      innerRef={commentBox => this.commentBox = commentBox.getRenderedComponent()}
    />
    

    I'm just conjecturing here. I've never attempted this pattern myself.