Skip to content

Provider / Context

In order to use the Provider, you for now to use React as the render library.

Many components have some default translated strings. But also other things like the default currency and so on, cab be controlled globally by using a Provider. Changing the properties of the provider, will automatically update all the components who has used a value from it.

Here are some example usage of the Provider / Context relation ship.

Changing locale or currency

You can either set the locale as a properly e.g. <Provider locale="en-US" ... and handle the change from the app root, or change it inside the app, respective Context:

import Provider from 'dnb-ui-lib/shared/Provider'
import Context from 'dnb-ui-lib/shared/Context'
const ChangeLocale = () => {
const { setLocale, update, locale } = React.useContext(Context)
React.useEffect(() => {
// Change the locale
update({ locale: 'en-US' })
// Change the default currency
update({ currency: 'USD' })
}, [])
return (
<Dropdown
value={locale}
data={{ 'en-US': 'English', 'nb-NO': 'Norsk' }}
on_change={({ data: { selected_key } }) => {
setLocale(selected_key)
}}
/>
)
}
render(
<Provider>
<MyApp>
<ChangeLocale />
text <Number>123</Number> table etc.
</MyApp>
</Provider>
)

Nested Providers

Yes, it's possible to have nested providers.

You have then to decide what you need to update.

import Provider from 'dnb-ui-lib/shared/Provider'
import Context from 'dnb-ui-lib/shared/Context'
const ChangeLocale = () => {
const { setCurrentLocale, updateCurrent, locale } = React.useContext(
Context
)
React.useEffect(() => {
// Change the locale
updateCurrent({ locale: 'en-US' })
// Change the default currency
updateCurrent({ currency: 'USD' })
}, [])
return (
<Dropdown
value={locale}
data={{ 'en-US': 'English', 'nb-NO': 'Norsk' }}
on_change={({ data: { selected_key } }) => {
setCurrentLocale(selected_key)
}}
/>
)
}
render(
<Provider locale="en-US">
<MyApp>
<Provider locale="nb-NO">
Norsk <Number>1234</Number>
<ChangeLocale />
</Provider>
English <Number>1234</Number>
</MyApp>
</Provider>
)

Provider and context troubleshooting

If there is a module format deviation, components do not share anymore the same provider and context. So, make sure you have a consistent import routine, not like this:

// NB: Example of deviant module formats
import Provider from 'dnb-ui-lib/shared/Provider' // like /esm
import { Button } from 'dnb-ui-lib/es'
import { Number } from 'dnb-ui-lib/cjs/components'