DEV Community

Discussion on: Creating Floating Label/Placeholder for Input with ReactJS

Collapse
 
andrewandopen profile image
andrew-andopen • Edited

Really useful, thank you! I've replicated everything from above and have run in to a bit of trouble when I have multiple inputs fields.

Typing in to one field sets the isActive state to true, as a result adding the label styling to all inputs, not just the single input I have populated. Any suggestions on how to work around this?

Thanks

Collapse
 
rafacdomin profile image
Rafael Domingues

Separate this input into a component and use that component instead so that each input will have a different isActive state, or manually create a different property isActive for each input you will use

Collapse
 
fernandosf profile image
FernandoSF

Insted of using a className, I add the "required" Attribute on input, and in the css use "valid" insted "focus-within".

The result is similar, i donΒ΄t use the transform

Here is a part of my code:

CSS

export const Input = styled.div`
  width: 100%;
  position: relative;
  margin: 20px 0px 30px;
  input,
  select {
    width: 100%;
    border: 0;
    border-bottom: 2px solid #cacaca;
    padding: 5px;
    position: absolute;
    &:valid {
      border-color: #3492eb;
      + label {
        position: absolute;
        top: -12px;
        color: #3492eb;
        padding: 0px;
        font-size: 12px;
      }
    }
  }
  label {
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: 1;
    padding: 5px;
  }
`;
Enter fullscreen mode Exit fullscreen mode

index.js

            <Input>
              <input
                required
              />
              <label>Entry 1</label>
            </Input>
            <br/>
            <Input>
              <input
                required
              />
              <label>Entry 2</label>
            </Input>
Enter fullscreen mode Exit fullscreen mode

Image description