Roy
Roy

Reputation: 1922

Looping through custom react components and adding className's to them

I want to loop through custom React elements using .map(). An example of what i'm looping through is:

<Button text="Click me" />
<Button text="Click me" bgColor="yellow" textColor="black"/>
<Button text="Click me" bgColor="limeGreen" onClick={() => console.log('clicked')}/>
<Button text="Click me" bgColor="orchid"/>
<Button text="Click me" bgColor="rgb(150, 20,0)"/>

I have component called Container that takes these children as a property:

export const Container = ({children}) => {

    return (
        <div>{children}</div>
    )
}

I tried to implement the looping like:

const newChildren = children.map((item) => {
    //add class name to every item
})

//

<div>{newChildren}</div>

However I'm stuck at this point. How can I add a className attr to all of the items?

Upvotes: 0

Views: 824

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

children prop is a ReactElement (an object and not an array).

You need to use React.Children API in order to be able to map children.

Then use React.cloneElement for passing the className property.

Working Example:

// styles.js
.button {
  background: red;
}

// App.js
import "./style.css";

const Container = ({ children }) => {
  return (
    <div>
      {React.Children.map(children, (child, key) =>
        React.cloneElement(child, { className: "button", key })
      )}
    </div>
  );
};

const App = () => {
  return (
    <Container>
      <button>Give me some color!</button>
    </Container>
  );
};

Edit angry-bardeen-fhblm

Upvotes: 2

Related Questions