Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styled component input focus

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>
    )
  }
}
like image 586
quantdaddy Avatar asked Jul 12 '18 08:07

quantdaddy


2 Answers

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

like image 137
Flemin Adambukulam Avatar answered Sep 18 '22 17:09

Flemin Adambukulam


Please try this

import React from 'react';
import styled from 'styled-components';

const UrlInput = styled.input`
  background-color: white;
`;

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

  componentDidMount() {
    if (this.inputRef.current) {
      this.inputRef.current.focus(); // This should work
    }
  }

  render() {
    return(
        <UrlInput innerRef={this.inputRef} />
    )
  }
}

You can use ref instead of innerRef if you switch to React v16 and styled components v4

<UrlInput ref={this.inputRef} />

And also please check this

Native support for ref on any styled component, no more innerRef thanks to React v16

https://medium.com/styled-components/announcing-styled-components-v4-better-faster-stronger-3fe1aba1a112

like image 37
Uday Sravan K Avatar answered Sep 18 '22 17:09

Uday Sravan K