Search code examples
reactjsinputstyled-components

How to add style to a input component with React?


In a customized input component

import React, { InputHTMLAttributes } from "react";
import styled, { css } from "styled-components";

type InputTypeProps = {
  disabled: boolean;
};

export const MyInput: React.FC<InputHTMLAttributes<HTMLInputElement>> = (
  disabled,
  props
) => {
  return <Input type="text" disabled={disabled} {...props} />;
};

const Input = styled.input`
  ${() => css<InputTypeProps>`
    background-color: ${({ disabled }) => (disabled == false ? "white" : "gray")};
  `}
`;

When use this component as

import { MyInput } from "~/components";

const Home: NextPage = () => {
  const disabled = false;
  return (
    <MyInput name="input1" disabled={disabled} />
  );
};

It alwasy show gray color when I set disabled to true or false. It seems this way doesn't work. Is it possible to handle this html property to change in React way?


Solution

  • Change to this.

    const Input = styled.input`
    background-color: white;
    &:disabled {
       background-color: gray;
    }
    `;