When using an html input with styled-components and saving the value to react state with onChange, the component appears to be re-rendering on every state change and causing the input to lose focus. Is there any way to prevent the input from losing focus? Why is this occurring? Here is an example.
class MyComponent extends React.Component {
state = { val: "" };
render() {
const Input = styled.input`
border-radius: 6px;
`;
return (
<Input
value={this.state.val}
onChange={e => this.setState({ val: e.target.value })}
/>
);
}
}
styled.input
creates a new legit react component. It should be defined outsideMyComponent
. If you intend to define styles exclusively for a particularinput
without defining a separate component, consider using css prop. – ron4ex