Search code examples
cssreactjsreact-hooksstyled-components

Overlap Left Part Input using Styled Components in React


I need to overlap the left part of the Input using styled-components in React. He will be able to write only after the overlap, on the right part.

Codesandbox is here CLICK HERE

Just like this image below:

enter image description here

const TextInput = styled.input`
  font-size: 16px;
  padding: 10px 10px 10px 10px;
  display: block;
  border: 2px solid #e3e5e5;
  border-radius: 8px;
  height: 28px;
  width: 100%;
  &:focus {
    outline: none;
  }
`;

Solution

  • I would push the border styling and layout to the Wrapper component. Add a styled label component.

    enter image description here

    Code

    const Wrapper = styled.div`
      width: 100%;
      position: relative;
      margin-bottom: 1rem;
      display: flex;
      flex-direction: row;
      border: 2px solid #e3e5e5;
      border-radius: 8px;
      overflow: hidden;
    `;
    
    const InputLabel = styled.label`
      background-color: #e3e5e5;
      color: gray;
      display: flex;
      flex-direction: column;
      font-size: 16px;
      height: 28px;
      justify-content: center;
      padding: 10px;
      width: auto; // <-- can set to specific width for consistency
    `;
    
    const TextInput = styled.input`
      border-width: 0;
      flex: 1;
      font-size: 16px;
      height: 28px;
      padding: 10px;
      outline: none;
    `;
    
    const TextError = styled.span`
      display: block;
      font-size: 12px;
      color: #ff0000;
      line-height: 14px;
      font-weight: bold;
      margin-top: 11px;
    `;
    
    const Input = ({
      label,
      name,
      type = "text",
      value = "",
      handleChange = () => {},
      error = null,
      touched = false
    }) => {
      return (
        <div>
          <Wrapper>
            <InputLabel htmlFor={name}>{label}</InputLabel>
            <TextInput
              id={name}
              name={name}
              type={type}
              value={value}
              onChange={handleChange}
            />
          </Wrapper>
          {error && touched && <TextError>{error}</TextError>}
        </div>
      );
    };
    

    Edit overlap-left-side-input-styled-components (forked)