createContext<TValue> function
Context<TValue>
createContext<TValue>([
- TValue? defaultValue,
- int calculateChangedBits(
- TValue? currentValue,
- TValue? nextValue
Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.
The defaultValue
argument is only used when a component does not have a matching Context.Provider
above it in the tree. This can be helpful for testing components in isolation without wrapping them.
Example:
react.Context MyContext = react.createContext('test');
class MyContextTypeClass extends react.Component2 {
@override
final contextType = MyContext;
render() {
return react.span({}, [
'${this.context}', // Outputs: 'test'
]);
}
}
___ OR ___
react.Context MyContext = react.createContext();
class MyClass extends react.Component2 {
render() {
return MyContext.Provider({'value': 'new context value'}, [
MyContext.Consumer({}, (value) {
return react.span({}, [
'$value', // Outputs: 'new context value'
]),
});
]);
}
}
Learn more: https://reactjs.org/docs/context.html#reactcreatecontext
Implementation
Context<TValue> createContext<TValue>([
TValue? defaultValue,
int Function(TValue? currentValue, TValue? nextValue)? calculateChangedBits,
]) {
final jsDefaultValue = ContextHelpers.jsifyNewContext(defaultValue);
ReactContext JSContext;
if (calculateChangedBits != null) {
int jsifyCalculateChangedBitsArgs(currentValue, nextValue) {
return calculateChangedBits(
ContextHelpers.unjsifyNewContext(currentValue) as TValue?,
ContextHelpers.unjsifyNewContext(nextValue) as TValue?,
);
}
JSContext = React.createContext(jsDefaultValue, allowInterop(jsifyCalculateChangedBitsArgs));
} else {
JSContext = React.createContext(jsDefaultValue);
}
return Context(
ReactJsContextComponentFactoryProxy(JSContext.Provider, isProvider: true),
ReactJsContextComponentFactoryProxy(JSContext.Consumer, isConsumer: true),
JSContext,
);
}