Answers for "react children props"

4

react props.children proptype

import PropTypes from 'prop-types'

...

static propTypes = {
    children: PropTypes.oneOfType([
        PropTypes.arrayOf(PropTypes.node),
        PropTypes.node
    ]).isRequired
}
Posted by: Guest on November-11-2020
2

react pass props to children

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

const Child = ({ doSomething, value }) => (
  <div onClick={() => doSomething(value)}>Click Me</div>
);

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 <div>{childrenWithProps}</div>
  }
};

ReactDOM.render(
  <Parent>
    <Child value="1" />
    <Child value="2" />
  </Parent>,
  document.getElementById('container')
);
Posted by: Guest on August-06-2020
0

react render props children

render() {
    return (
      <div>
        <LoadContent>
          {
            ({ loading }) => <span>{loading}</span>
          }
        </LoadContent>
      </div>
    )
  }
Posted by: Guest on April-19-2021
0

react render props children

<LoadContent url="https://yourendpoint.com">
  {({ loading, error, data }) => {
    if (loading) return <span>Loading...</span>;
    if (error) return <span>Error loading</span>;

    return (
      <div>
        {data.map((item) => (
          <div>{item}</div>
        ))}
      </div>
    );
  }}
</LoadContent>
Posted by: Guest on April-19-2021

Code answers related to "react children props"

Code answers related to "Javascript"

Browse Popular Code Answers by Language