styled component input focus

quantdaddy picture quantdaddy · Jul 12, 2018 · Viewed 6.9k times · Source

I'm trying to focus on the input when the component mounts. The input component is a styled component, therefore I use innerRef to get the reference to the element. However the input does not get focus when the component mounts. I have checked that the node is actually getting the reference to the DOM node. I m not able to find any issue with my logic. Thank you for your help.

import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';
import styled, { keyframes } from 'styled-components';

const UrlInput = styled.input`
  width: 400px;
  height: 34px;
  background-color: white;
  display: inline-block;
  outline: none;
  padding-left: 10px;
  font: 400 14px 'Source Sans Pro', 'sans-serif';
  ::placeholder {
    color: rgb(100,100,100);
    font: 400 14px 'Source Sans Pro', 'sans-serif';
  }
`

class AddUrl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      url: ''
    }
    this.inputRef = React.createRef();
  }

  componentDidMount() {
    const node = findDOMNode(this.inputRef.current);
    node && node.focus();
  }


  render() {
    return(
      <AddUrlWrapper>
        <UrlInput placeholder={"Paste URL here"}
          innerRef={this.inputRef}
          type="text"
          value={this.state.url}
          onChange={(event) => this.setState({url: event.target.value})}/>
        <FetchButton>Fetch</FetchButton>
      </AddUrlWrapper>
    )
  }
}

Answer

Flemin Adambukulam picture Flemin Adambukulam · Oct 5, 2018

For styled components, use the prop innerRef instead of ref. Got it from their docs here.

Example from the doc:

<StyledInput innerRef={this.input} />

Gave it a try, it works