React.cloneElement use

Using React.cloneElement to style component children from this.props.children

by jonahe

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

.done {
  color: rgba(0, 0, 0, 0.3);
  text-decoration: line-through;
}

input {
  margin-right: 5px;
}

React

class TestWrapper extends React.Component {
  constructor(props) {
    super(props)
    this.state = {};
  }
  
  render() {
  	console.log(this.props.children)
    console.log('toArray', React.Children.toArray(this.props.children));
    const children = React.Children.map(this.props.children, (child, i) => {
    	console.log('child nr ' + i + 1, child.props )
      const newProps = {...child.props, style: {...child.props.style, color: "green"}};
    	return React.cloneElement(child, newProps);
    })
    return (
    <div>{children}</div>
    )
  }
}


class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = { };
  }
  
  render() {
    return (
      <div>
        <TestWrapper>
          <div key="1" style={{fontSize: 33, background: 'blue'}} ><div><h3>tester</h3></div> </div>
          <div key="2" >second </div>
        </TestWrapper>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))