Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - adding class to children components

Tags:

im using react and I have a component that simply needs to render the children and add them a class according to a condition. Whats the best way of doing it?

like image 318
Golan Kiviti Avatar asked Aug 30 '16 11:08

Golan Kiviti


People also ask

Can React components have children?

React Components and Children In React, a component can have one, many, or no children.

How do you pass Props to child component in React?

There is no way to pass props up to a parent component from a child component. We will revisit this caveat later in this tutorial. It's also important to note that React's props are read only (immutable). As a developer, you should never mutate props but only read them in your components.


2 Answers

I figured it out a week ago, this is what I wanted :

export default class ContainerComponent extends React.Component {     constructor(props) {         super(props);          this.modifyChildren = this.modifyChildren.bind(this);     }      modifyChildren(child) {         const className = classNames(             child.props.className,             {...otherClassses}         );          const props = {             className         };          return React.cloneElement(child, props);     }     render() {         return (<div>             {React.Children.map(this.props.children, child => this.modifyChildren(child))}         </div>);     } } 
like image 51
Golan Kiviti Avatar answered Oct 14 '22 01:10

Golan Kiviti


For the sake of simplicity:

const StyleInjector = ({ children }) => {    const StyledChildren = () =>     React.Children.map(children, child =>       React.cloneElement(child, {         className: `${child.props.className} ${PUT_YOUR_CLASS_HERE}`       })     );    return <StyledChildren />; }; 
like image 37
Kerem atam Avatar answered Oct 14 '22 02:10

Kerem atam