React Context API not working from custom NPM component library - javascript

I've built a ReactJS component library that I use for multiple projects installed via an NPM package using a sim link. I want to use the context API to pass data from a parent component served from the component library to my base project to be consumed by multiple consumer components also served from the component library. When I try the context is always undefined in my child components.
If I place my consumer component in my provider component within my library it works like a champ but this defeats what I'm trying to achieve. If I export both the provider and the consumer to my base project the consumer doesn't see the provider.
This is from my base project
import { Screen, COD, GenericSocketServer } from 'component-library'
export default class View extends React.PureComponent {
render() {
return (
<Screen className="screen odmb1">
<GenericSocketServer>
<COD />
</GenericSocketServer>
</Screen>
)
}
}
This is my provider code exported from my 'component-library'
import React from 'react';
import MyContext from "./context";
import COD from './../cod';
export default class GenericSocketServer extends React.Component {
render() {
return (
<MyContext.Provider value={{ foo: 'bar' }}>
<COD />
{this.props.children}
</MyContext.Provider>
);
}
}
This is my content code used in 'component-library'
import React from 'react'
const MyContext = React.createContext()
export default MyContext
This is my consumer component exported from 'component-library'
import MyContext from "../GenericSocketServer/context"
class COD extends React.Component {
render() {
return (
<React.Fragment>
<MyContext.Consumer>
{(context) => {
/*
context comes back undefined
I expect { foo: 'bar' }
*/
console.log('context :', context)
return (
<p>This should work</p>
)}}
</MyContext.Consumer>
</React.Fragment>
)
}
}
Context always comes back undefined as if it doesn't see the parent provider. I think I'm ether doing something wrong initializing the context myself or for some reason the two components I'm importing just don't share the same context. Please help!! Not sure if I should give up on this and just use redux.

Maybe you are making multiple instances of the component providing the context. Let's say you have a component Sound, which starts by:
const { Provider, Consumer } = React.createContext();
If you import this library from your main project, the context will be created at the global space. You then use it to render your document tree. But in another component you also imported this library, which had to be resolved during webpack transpilation. It thus has its own copy of the above lines and a context object created in its own space. The problem occurs when you try to use the Consumer, because the Provider was only made by the main project for the first context object, and the second context's provider instance was never instantiated, thus returns undefined.
A solution to the problem is to enforce a single context object, which you can achieve by telling the second component's webpack that the provider-owning library is an external, so when webpack reaches e.g. the "import sound" line, it will not go further and will assume this dependency is resolved at runtime. When runtime comes, it will take it from the same place where the main project is taking it. To do this in webpack, e.g. for above "sound" library, add this to your other component (not main project):
{
...
externals: {
...
'sound': 'sound'
}
...
}
Also in your component package.json:
{
...
peerDependencies: {
"sound": "^1.2.3"
}
}

Apart from Darko's answer, esm and cjs export is also a possible reason for context to fail in a package. If you use the hook in esm and the provider in cjs, you will not get the value for that context.

I recently had a similar issue where I was trying to consume the value of a context inside my library components but using the provider (imported from the package) in the host app.
I managed to solve the issue just by making react and react-dom external and peerDependencies when bundling in rollup.

should your code of consumer be
<React.Fragment>
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
</React.Fragment>
as stated from the official react doc : https://zh-hant.reactjs.org/docs/context.html
when you define
you can use it like

Related

Persist data between two pages with Next.js

I would like to refactor my Next.js webapp to have different pages handle different screens. Currently, I have this component holding several states to know in which screen I'm in. In the jsx section, I'm using {value && ... } to render the right component.
But I feel this is not good design, and won't be maintainable when adding more and more screens.
I would also like to avoid Redux as it is overkill for my project.
I was thinking about persisting data in cookies so I can retrieve them with getInitialProps in every component when rendering a new page, but is there a more elegant way?
I've read about tweaking the _app.js but I'm not sure to understand the consequences of doing so, and how it could help me..
Any suggestion?
When multiple of your pages need to make use of same data, you can make use of Context to store the result. It a good way to make a centralized storage without using complex and more self sufficient libraries like redux
You can implement context inside of _app.js file which must reside inside your root folder. This way next.js treats it as a root wrapper and you would just need to use 1 instance of Context
contexts/appContext
import React from 'react';
const AppContext = React.createContext();
export const AppProvider = AppContext.Provider;
export const AppConsumer = AppContext.Consumer;
export default AppContext;
_app.js
import React from 'react'
import App from 'next/app'
import AppProvider from '../contexts/appContext';
class MyApp extends App {
state={
data:[]
}
render() {
const { Component, pageProps } = this.props;
// You can implement logic in this component to fetch data and update state
return (
<div>
<AppProvider value={this.state.data}> // pass on value to context
<Component {...pageProps} />
</AppProvider>
</div>
)
}
}
export default MyApp
Now further each component can make use of context value by using AppConsumer or using useContext if you use hooks
Please read more about how to use Context here

How does import work with react?

My broader question is does an import of a module get shared between two components and why?
First what do I know about import. You can import in two different ways.
1.
At the top of your file which loads the imported module into a variable which you then can use.
import Highcharts from './highcharts'
// create a chart
Highcharts.Chart()
2.
Or dynamically anywhere in your code which returns a promise:
import('./highcharts').then((response) => {
// create chart
response.Chart();
});
But there is this weird behavior I don't understand when using import with react. If I have the following component:
import React, {Component} from 'react';
import Highcharts from 'highcharts/js/highcharts';
export default class Chart extends Component {
state = {
chartOptions: {
// my chart options and data
}
}
componentDidMount() {
if(this.props.extendFunc) {
import('highcharts/js/modules/funnel.src.js').then((funnelModule) => {
funnelModule(Highcharts)
})
}
Highchart.Chart('myChart', this.state.chartOptions)
}
render() {
<div id="myChart" />
}
}
I use the component from above twice. Now there is this behavior that both components use the same import e.g. the import of Highcharts does not happen twice. I noticed this because with Highcharts there is the option of extending the functionality.
If I for example extend the functionality for Chart 1 by passing a prop to extend it, the functionality of Highcharts is also extended in Chart 2, although I didn't pass a prop to extend the functionality.
import React, {Component} from 'react';
import Chart from './Chart';
export default class Dashboard extends Component {
render() {
return (
<div>
<Chart extendFunc={true}> Chart 1 </Chart>
<Chart> Chart 2 </Chart>
</div>
)
}
}
What causes this behavior? Is this react or is this just the way import works? Are imports global for multiple instances of the same component? Or are imports of a node module the same for the whole application?
What causes this behavior? Is this react or is this just the way import works? Are imports global for multiple instances of the same component? Or are imports of a node module the same for the whole application?
This is the way imports work. When you import something for the first time, the file is run and the exported values from it are returned back to the one importing it. When something is imported again, those same exports are reused and returned. Node JS modules work the same way.
Sometimes this behavior is helpful, firstly for performance to avoid unnecessarily re-running the same file over again, and also if the module wants to store some internal state. For example, counting the number of times a function is called from anywhere in the application.
In cases like this, where you need a single instance of something for each script, modules will usually give you a way to actually make an instance of that thing. For example, I might have a logging module, which exports a Logger class, then I can make new instances of that class for each component, and configure each logger separately.
For your case, look in the docs to see if there's a way to make per-component instances of Highcharts and extend that individual instance with the functionality you need.
When you extend <Chart /> with a prop extendFunc it will be extended in your Chart Component and not in your "new" Component.
That means, if you call the component, it will always have the props you gave it, but you will not have to use them (if there are not set as required).

React native: export default App with multiple module wraps

I Have the following App.js in my react native project:
class App extends Component {
render() {
return (
<ApolloProvider store={store} client={client}>
<AppWithNavigationState />
</ApolloProvider>
);
}
}
export default App = codePush(App);
I am trying to add aws amplify authenticator to my project (https://github.com/aws/aws-amplify/blob/master/media/quick_start.md#react-native-development) but the steps tell me to add :
export default withAuthenticator(App);
^^ How do I do that when I have already codePush wrapped around the App component that I am exporting?
TL;DR:
The withAuthenticator is basically a higher order component which takes a component, decorates it (i.e. provide some special props or customizations of sorts) and returns a new component composed of the component you passed in. So in your case if you want multiple HOCs, you can simply say -
export default withAuthenticator(codePush(App))
This syntax can get potentially nasty from a readability standpoint if you have, say, 5 decorators. It is useful in such cases to use the new decorator syntax. With it you can do neat things like -
#mySpecialDecoratorThatDoesNiceThings
#withAuthenticator
#codePush
export default class App extends Component {
...
}
If you are using babel, check out this transform-decorators babel plugin to make sure decorators are correctly transpiled.

Why HOC are applied during exporting of component in place of importing it

My basic understading is that HOC like connect (for connecting with redux store) and other HOC's are applied to a component while exporting it.
Like this
import React, { Component } from 'react';
import './App.css';
import myHoc from './myHoc/index';
class App extends Component {
render() {
return (
<div className="App">
</div>);
}
}
export default myHoc({})(App);
Where as a better thing would be to apply HOC during import as it would make it easier to make reusable component. The same component can pick up props from store or from props and that would be the responsibility of the parent component to check what to give which HOC to apply on the component.
I know we can use container components which takes the component and render children but that just adds code in the JSX (wont look good if there are many container components)
though we can do it like this
import React, { Component } from 'react';
import './App.css';
import myHoc from './myHoc/index';
import AppChild from './AppChild';
const NewAppChild = myHoc({}, ()=> {
})(AppChild);
class App extends Component {
state = {
count: 1,
};
reRender = () => {
this.setState({count: this.state.count + 1});
};
render() {
return (
<div className="App">
<NewAppChild handleClick={this.reRender} count={this.state.count}/>
</div>
);
}
}
export default App;
What my question is that, is there something better that can handle this kind of situations where I want to apply my HOC on import that is each many container components can import it and they can apply different HOCs depending on the needs.
There is no single concrete reason for this design choice - as you have already seen you can invoke your HOC wherever you use the component - but I see at least 1 advantage: configuration & component reuse.
In your example, myHoc takes no parameters or configuration so this doesn't necessarily apply, but imagine instead that you are invoking connect from redux.
In most use cases, connect accepts 2 configuration functions -
mapStateToProps & mapDispatchToProps - that define the behaviour. If you define those within MyComponent then any consuming component can import MyComponent from 'MyComponent' and start using it.
If you instead rely on the parent component to call connect() then you are forcing every consumer to re-implement the configuration of connect as well. That may mean many instances of duplicated configuration and adds to the complexity for consuming components.
That being said, there are certainly cases where you might want this behaviour - for example, if you wanted to connect the same component to different state definitions. Ultimately you need to pick the best pattern to support what you need from the component.

Construct React Component from a React Element

I'm trying to create a "higher-order" function in React that performs some permissions-based checks on the wrapped component and returns it accordingly.
MyComponent.js
...
export default Permissions(MyComponent)
Permissions.js
export default function Permissions(Component) {
class NewComponent extends React.Component {
// ... perform checks here
render() {
return {validPermissions && <Component />}
}
}
}
However, I'd like to be able to use this Permissions as a React Component (as opposed to a function that wraps the component export).
It would looks similar to this:
<Permissions>
<MyComponent />
</Permissions>
When I run React.Component.isPrototypeOf(Component.children) I get false in these instances. My inclination is to think that the solution is to use some React or ReactDOM method to transform the React Element into a React Component, and then perform the same checks.
How can I transform a React Element into a React Component?
Update:
I gave the bit about permissions as context, but not looking for help with regard to implementing permissions.
I am basically looking for the opposite of React.createElement(MyComponent).
You can use a functional component, which combines the best of both worlds: it's simple (just a function!) and at the same time it's a proper stateless React component.
const Permissions = ({ granted, children }) =>
granted ? React.Children.only(children) : null;
Usage:
<Permissions granted={true}>
<MyComponent />
</Permissions>

Categories

Resources