0

I'd like to make reusable styled components where each component has its default attributes but for specific things, like size, I'd like to specify with each use of the component.

For example, I have this InputField Component:

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

const InputFieldContainer = styled.input`
  background: #252c37;
  border-radius: 15px;
  border: 0px;
  width: 80%;  ///   THESE TWO I HAVE 
  height: 75px; //   HARDCODED THE SIZE 
  font-size: 30px;
  color: white;
  padding-left: 15px;
  margin-bottom: 30px;
  &::placeholder {
    color: white;
  }
`;

function InputField(props) {
  return (
    <div>
      <InputFieldContainer
        type={props.type}
        value={props.value}
        name={props.name}
        placeholder={props.placeholder}
        onChange={props.onChange}
      />
    </div>
  );
}

export default InputField;

However, every time I use this component, I want to be able to change some values (like width and height) with each use. In other words, I do not want to hard code some CSS values, just gain the ability to be able to specify them once they are used.

For example:

<InputField
      type="password"
      value={null}
      placeholder="password"
      label="password"
      name="password"
      onChange={null}
      width = "100px". // I know this isn't possible, but used as example
 ></InputField>

I know there may be ways around this using CSS by using it's priority list (inline CSS etc.) but surely there's a more robust/cleaner way?

Yossi
  • 5,577
  • 7
  • 41
  • 76
Nathan
  • 1,393
  • 1
  • 9
  • 40
  • Check this answer [link](https://stackoverflow.com/questions/52321539/react-passing-props-with-styled-components) – Medi Apr 15 '21 at 18:25

1 Answers1

2

You could pass them as props like this. More information about this in the docs:

const InputFieldContainer = styled.input`
  background: #252c37;
  border-radius: 15px;
  border: 0px;
  width: ${({ width }) => width};
  height: ${({ height}) => height};
  font-size: 30px;
  color: white;
  padding-left: 15px;
  margin-bottom: 30px;
  &::placeholder {
    color: white;
  }
`;

function InputField(props) {
  return (
    <div>
      <InputFieldContainer {...props}/>
    </div>
  );
}

export default InputField;
Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • How would I do the same for components that I reference outside it's class? For an example check the last block of code at the bottom of my answer? E.g. `` etc... – Nathan Apr 15 '21 at 18:31
  • I've updated with how to forward the props – Guerric P Apr 15 '21 at 18:37
  • 1
    My bad, forgot to add it to the const attribute, great answer, thanks for the docs. – Nathan Apr 15 '21 at 18:39