Search code examples
reactjsstylesborderstyled-components

How can React Js make a Border-botom as a function?


I would like to give Border-bottom as a function. What should I do?

This is the code that Border-bottom should appear.👇

import React from "react";
import { Header } from "../BaseLabel";
import { Link, withRouter } from "react-router-dom";

const Header = ({ location: { pathname } }) => {
 const getStyle = (path) => {
    return {
      color: pathname === path ? "#191919" : "#B6B6B6",
      borderBottom: pathname === path ? "#191919" : null,
    };
  };
return (
    <>
   <ShapMenu>
       <ShapLinks to="/covid19" style={getStyle("/covid19")}> //Link
           <Header title="코로나19" current={pathname === "/covid19"} />
       </ShapLinks>
   </ShapMenu>
    </>
   );
}

This is Header Styled-components👇

const ShapMenu = styled.div`
  display: flex;
  box-sizing: content-box;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
  scroll-behavior: smooth;
  scrollbar-color: inherit;
  cursor: pointer;
`;
const ShapLinks = styled(Link)``;

This is a reusable component code. This code is not only used on this screen because it is a reuse code.👇

import PropTypes from "prop-types";
import styled from "styled-components";
import React from "react";

export const Header = ({ title, children }) => {
  return (
    <>
      <Title>{title}</Title>
      <Items>{children}</Items>
    </>
  );
};
Header.propTypes = {
  title: PropTypes.node,
  children: PropTypes.object,
};

const Items = styled.div``;
const Title = styled.div`
  margin-right: 14px;
  font-size: 20px;
`;

This is the style property that I want to give to the title.👇

border-bottom: 2px solid
      ${(props) => (props.current ? "#191919" : "transparent")};
    transition: border-bottom 0.5s ease-in-out;

Solution

  • The CSS styled rules appear to be correct. You should pass the current prop from Header to Title.

    const Header = ({ current, title, children }) => { // <-- destructure current
      return (
        <>
          <Title current={current}>{title}</Title> // <-- pass current prop
          <Items>{children}</Items>
        </>
      );
    };
    Header.propTypes = {
      children: PropTypes.object,
      current: PropTypes.bool,
      title: PropTypes.node
    };
    
    const Title = styled.div`
      margin-right: 14px;
      font-size: 20px;
    
      border-bottom: 2px solid
        ${(props) => (props.current ? "#191919" : "transparent")}; // <-- use current prop
      transition: border-bottom 0.5s ease-in-out;
    `;
    

    Edit how-can-react-js-make-a-border-botom-as-a-function