0
votes

In styled-components you can refer another React component by using this syntax ${Label} but works sometimes with some components and others don't.

I am trying already reading the documentation https://www.styled-components.com/docs/advanced#referring-to-other-components and when I start building a component I wasn't possible to do it with a Label component, only works with a div component.

I update the styled-component to the latest stable version.

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

// https://codepen.io/lewisvrobinson/pen/EyZwjR
// VARIABLES // ============================== //
const bgColor = "#424242";
const hlColor = "#2196F3";
const mutedColor = "Black";
const transTime = "300ms";
const width = "320px";

// FORM // ============================== //

const Box = styled.div`
  position: relative;
  margin: 45px 0;
`;

const Input = styled.input.attrs({
  type: "text",
  required: "required"
})`
  background: none;
  color: ${mutedColor};
  font-size: 18px;
  padding: 10px 10px 10px 5px;
  display: block;
  width: ${width};
  border: none;
  border-radius: 0;
  border-bottom: 1px solid ${mutedColor};
  &:focus {
    outline: none;
  }
  &:focus ~ label,
  &:valid ~ label {
    top: -14px;
    font-size: 12px;
    color: ${hlColor};
  }
  &:focus ~ ${Bar}:before {
    width: ${width};
  }
`;

const Label = styled.label`
  color: ${mutedColor};
  font-size: 16px;
  font-weight: normal;
  position: absolute;
  pointer-events: none;
  left: 5px;
  top: 10px;
  transition: ${transTime} ease all;
`;

const Bar = styled.span`
  position: relative;
  display: block;
  width: ${width};
  &:before {
    content: "";
    height: 2px;
    width: 0;
    bottom: 0px;
    position: absolute;
    background: ${hlColor};
    transition: ${transTime} ease all;
    left: 0%;
  }
`;

const TextField = props => {
  return (
    <Box>
      <Input />
      <Bar></Bar>
      <Label>Name</Label>
    </Box>
  );
};

export default TextField;

As you can see in this lines

  &:focus ~ label,
  &:valid ~ label 

I am using the label base, and I want to use the Label component that I custom.

I need that works like this:

  &:focus ~ ${Label},
  &:valid ~ ${Label} 

The weird part is that in this line:

  &:focus ~ ${Bar}:before 

Bar works as expected.

1

1 Answers

1
votes

It is because when you are using ${Label} in the Input component it does not exist yet. Move it up the file and it should work as expected.

Example: https://codesandbox.io/embed/zen-cloud-f8mht