Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extend default className component

Hey I use bootstrap with React and I try figure out, how I can extend my component by passing className props deeper. In my atom component I have two files. First one with component declaration.

Breadcrumb.js

export const Breadcrumb = (props) => {
  const { className } = props;
  const classes = getClasses(className);

  return (
    <Link to={props.path} className={classes} {...props}>
      {props.children}
    </Link>
  );
};

and another one with getClasses() which returns all default BS classes.

Breadcrumb.style.js

export const getClasses = (extra = "") => {
  const defaultClasses = getDefaultClasses();
  const addingClasses = extra;
  const classes = `${defaultClasses} ${addingClasses}`;

  return classes;
};

const getDefaultClasses = () => `ps-3 fs-3 fw-bold text-decoration-none`;

What I want to achieve is, when I’ll invoke my Breadcrumb component, and I’ll decied to extend it on extra classes I can do that by pass className props…like

TopBar.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export const TopBar = () => {
  const breadcrumbs = useBreadcrumbs(routes, { disableDefaults: true });
  const classes = getClasses();

  return (
    <div className={classes}>
      {breadcrumbs.map(({ match, breadcrumb }) => (
        <Breadcrumb
          path={match.pathname}
          children={breadcrumb}
          className="cs_breadcrumb"
          key={uuidv4()}
        />
      ))}
    </div>
  );
};

But when I do that, my declare Breadcrumb className is override by invoke Breadcrumb className… Although in Breadcrumb.js console.log(classes) returns concated classes.
Anyone knows how to achieve that or has any tips ?? I’ll be glad

>Solution :

Change

export const Breadcrumb = (props) => {
  const { className } = props;
  const classes = getClasses(className);

  return (
    <Link to={props.path} className={classes} {...props}>
      {props.children}
    </Link>
  );
};

to

export const Breadcrumb = ({ className, ...rest }) => {
  const classes = getClasses(className);

  return (
    <Link to={props.path} className={classes} {...rest}>
      {props.children}
    </Link>
  );
};

So, you need to extract the className prop in the place where props was, and also add ...rest for the rest props.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading