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>
)
}
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With