react add component props for each code example

Example 1: react pass props to children

import React, { Children, isValidElement, cloneElement } from 'react';

const Child = ({ doSomething, value }) => (
  
doSomething(value)}>Click Me
); function Parent({ children }) { function doSomething(value) { console.log('doSomething called by child with value:', value); } render() { const childrenWithProps = Children.map(children, child => { // Checking isValidElement is the safe way and avoids a TS error too. if (isValidElement(child)) { return cloneElement(child, { doSomething }) } return child; }); return
{childrenWithProps}
} }; ReactDOM.render( , document.getElementById('container') );

Example 2: props in react app

/* PASSING THE PROPS to the 'Greeting' component */
const expression = 'Happy';
 // statement and expression are the props (ie. arguments) we are passing to Greeting component

/* USING THE PROPS in the child component */
class Greeting extends Component {
  render() {
    return 

{this.props.statement} I am feeling {this.props.expression} today!

; } } -------------------------------------------- function Welcome(props) { return

Hello, {props.name}

; } const element = ; ReactDOM.render( element, document.getElementById('root') );

Tags:

Misc Example