I\'m trying to find the proper way to define some components which could be used in a generic way:
With the update to React 16.6 you can now use React.createContext and contextType.
import * as React from 'react';
// React.createContext accepts a defaultValue as the first param
const MyContext = React.createContext();
class Parent extends React.Component {
doSomething = (value) => {
// Do something here with value
};
render() {
return (
{this.props.children}
);
}
}
class Child extends React.Component {
static contextType = MyContext;
onClick = () => {
this.context.doSomething(this.props.value);
};
render() {
return (
{this.props.value}
);
}
}
// Example of using Parent and Child
import * as React from 'react';
class SomeComponent extends React.Component {
render() {
return (
);
}
}
React.createContext shines where React.cloneElement case couldn't handle nested components
class SomeComponent extends React.Component {
render() {
return (
);
}
}