Home > Blockchain >  Extend default className component
Extend default className component

Time:07-11

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

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

CodePudding user response:

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.

CodePudding user response:

I guess you want to extend component classes with other classes passed via props.

If I understand correctly, you can try like this:

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

  return (
    <Link to={props.path} className={[classes, className].join(" ")]} 
    {...props}>
      {props.children}
    </Link>
  );
};
  • Related