0

This is my current code:

// src/components/Main.tsx
import * as React from 'react';
import { ReactElement } from 'react';

import * as styles from '../styles/Main.module.scss';

type MainProps = {
  leftBtnGroup: ReactElement[],
  rightBtnGroup: ReactElement[],
  children: string,
};

const Main = ({ leftBtnGroup, rightBtnGroup, children }: MainProps) => (
  <>
    <div className={styles.main__btnBar}>
      <div className={styles.main__btnBar__leftBtnGrp}>
        {
          leftBtnGroup.map((btn) => {
            btn.props.className += ` ${styles.main__btnBar__btn}`;

            return btn;
          })
        }
      </div>
      <div className={styles.main__btnBar__rightBtnGrp}>
        {
          rightBtnGroup.map((btn) => {
            btn.props.className += ` ${styles.main__btnBar__btn}`;

            return btn;
          })
        }
      </div>
    </div>
    {children}
  </>
);

export default Main;

Two arrays of components are passed into the Main component as input and I want to add a class to each of these components. The function does not know what these components are (i.e. could be buttons, links, divs, or other components) but it can be asserted that they all have a className prop. How can I implement this? When I tried the above, I got this linting error:

ESLint: Assignment to property of function parameter 'btn'.(no-param-reassign)

2
  • If this is for styling, can't you just use a selector such as .main__btnBar__leftBtnGrp > *? Commented May 30, 2021 at 7:47
  • @Altareos That works but I'm trying to avoid using the wildcard as far as possible. Commented May 30, 2021 at 7:52

1 Answer 1

3

You should probably use React.cloneElement( https://reactjs.org/docs/react-api.html#cloneelement )

{
  leftBtnGroup.map(btn => {
    // I used ?? but you can use your choice of checking for existing
    // classes. Without checking, if they have no existing class this
    // would add an 'undefined' class where the existing classes go.
    return React.cloneElement(btn, { className: `${btn.props.className ?? ''} ${styles.main__btnBar__btn}` })
  })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.