declaration merging for react-native-elements theme - javascript

I am using react-native-elements in my react-native application.
My app is wrapped with the ThemeProvider to pass the theme down to all components.
<SafeAreaProvider>
<ThemeProvider theme={Theme}>
<Loader visible={loader.loading} text={loader.message} absolute={true} />
<RootNavigation />
</ThemeProvider>
</SafeAreaProvider>
In the theme file i define the values i want to use across the app.
const theme = {
colors: {
primary: '#6A69E2',
primaryDark: '#4747c2',
primaryLight: 'rgba(106, 105, 226, 0.35)',
gray: {
dark: '#242424',
default: '#666',
medium: '#999',
light: '#ccc',
lightest: '#e7e7e7',
},
},
text: {
size: {
small: 12,
default: 16,
large: 18,
h1: 26,
h2: 22,
h3: 20,
},
},
Text: {
style: {
fontSize: 16,
color: '#242424',
fontFamily: 'Roboto',
},
},
Button: {
style: {
borderRadius: 50,
},
disabledStyle: {
backgroundColor: 'rgba(106, 105, 226, 0.35)',
},
},
};
export default theme;
For the values the original theme of react-native-elements providing this is working. For example i can access the colors by using
const theme = useTheme()
theme.colors.primary
But when i want to add some new properties like primaryDark i'll get an linter error.
Object literal may only specify known properties, and 'primaryDark' does not exist in type 'RecursivePartial<Colors>'.ts(2322)
In the doc of react-native-elements is a part about declaration merging, but i don't understand how i can archive this
https://reactnativeelements.com/docs/customization/#typescript-definitions-extending-the-default-theme.
Somebody could help me with this?

Well, declaration merging still works. This seems like a bug on the lib's part.
Their doc says you can augment the Color interface in module 'react-native-elements'. But currently (as of 2021-04-18, with v3.3.2) that interface is actually hidden inside module 'react-native-elements/dist/config/colors', not directly exposed at the top level, weird.
I suggest you file an issue to their repo. Never mind, someone already filed the issue.
Tested on my machine, following solution works.
import React from 'react'
import { useTheme, ThemeProvider } from 'react-native-elements'
declare module 'react-native-elements/dist/config/colors' {
export interface Colors {
primaryDark: string
primaryLight: string
}
}
const ChildComp = () => {
const theme = useTheme()
theme.theme.colors.primaryDark // <-- No more error 🎉
return <div>foobar</div>
}
Reply to OP's comment. You can augment interface however you like, as long as the augmented key doesn't exist before. For example add foobar key to FullTheme.
declare module 'react-native-elements' {
export interface FullTheme {
foobar: string
}
}

Related

Next JS Chakra UI problem when trying to extend theme

I'm trying to extend the chakra ui theme but i get this error.
error - Error: Objects are not valid as a React child (found: object with keys {semanticTokens, direction, breakpoints, zIndices, radii, blur, colors, letterSpacings, lineHeights, fontWeights, fonts, fontSizes, sizes, shadows, space, borders, transition, components, styles, config}). If you meant to render a collection of children, use an array instead.
Here is my code.
import { extendTheme } from '#chakra-ui/react'
import { mode } from '#chakra-ui/theme-tools'
const styles = {
global: props => ({
body: {
bg: mode('#f0e7db', '#202023')(props)
}
})
}
const components = {
Heading: {
variants: {
'section-title': {
textDecoration: 'underline',
fontSize: 20,
textUnderlineOffset: 6,
textDecorationColor: '#525252',
textDecorationThickness: 4,
marginTop: 3,
marginBottom: 4
}
}
},
Link: {
baseStyle: props => ({
color: mode('#3d7aed', '#ff63c3')(props),
textUnderlineOffset: 3
})
}
}
const fonts = {
heading: "'M PLUS Rounded 1c'"
}
const colors = {
grassTeal: '#88ccca'
}
const config = {
initialColorMode: 'dark',
useSystemColorMode: true
}
const theme = extendTheme({ config, styles, components, fonts, colors })
export default theme

Exporting a custom theme from a UI library using Material-UI

I am creating a custom UI library for work that uses Material-UI. The UI library has a custom theme where I added to the palette object with custom company colors. The theme lives in the UI library, and for elements that live there, I can use the custom colors in makeStyles, but when I try to use the exported theme in the main codebase, the custom colors throw errors in makeStyles.
I believe the issue is I'm not exporting the theme's custom module. I am unsure how to export and import this correctly into the main codebase. Currently, I am only exporting the theme file and importing it into the main codebase.
Main Codebase:
import { theme } from 'customUILibrary';
...
<MuiThemeProvider theme={theme}>
...
</MuiThemeProvider>
CustomUILibrary:
index.ts:
export { theme } from 'theme/theme';
theme/theme.ts
import {
createTheme,
responsiveFontSizes,
} from '#material-ui/core/styles';
import './extendPalette';
export const theme = responsiveFontSizes(createTheme({
palette: {
gradients: {
primary: 'linear-gradient(270deg, #35C7E1 -10.76%, #1A92BD 121.8%)',
secondary: 'linear-gradient(270deg, #194E94 0%, #317CA6 100%)',
},
},
}));
extendPalette.ts
declare module '#material-ui/core/styles/createPalette' {
export interface PaletteOptions {
gradients: {
primary: string
secondary: string,
},
}
export interface Palette {
gradients: {
primary: string
secondary: string,
},
}
}
The custom theme attributes work great inside the UI Library with the UI elements, but when imported into the main codebase the custom attributes aren't being picked up, and in fact causing errors.
As suggested here, you can do something like this:
declare module "#mui/material/styles" {
interface Palette {
custom: {
pink: string;
};
}
interface PaletteOptions {
custom: {
pink: string;
};
}
}
Then you can set you value in theme safely:
const theme = createTheme({
palette: {
custom: {
pink: "pink"
}
}
});
and use it in styles:
<Button sx={{ color: "custom.pink" }}>Content</Button>
See my codesandbox example

In material-ui v5 How are you meant to override the styles of properties that don't exist in the themes components

I am trying to style MuiDataTables and am currently using the adaptv4theme to do it like below
declare module '#material-ui/core/styles/overrides' {
export interface ComponentNameToClassKey {
MUIDataTable: any;
MUIDataTableFilterList: any;
}
}
export const theme = createMuiTheme(
adaptV4Theme({
overrides: {
MUIDataTable: {
paper: {
boxShadow: 'none',
},
responsiveBase: {
overflow: 'clip',
},
},
MUIDataTableFilterList: {
chip: {
margin: '8px',
},
},
However adaptV4Theme is getting deprecated and do not know how to upgrade my code to the new convention as when I try
theme.components = {
...theme.components,
MUIDataTable:{
overrideStyles: {
},
},
I get the following error:
Object literal may only specify known properties, and 'MUIDataTable' does not exist in type 'Components'.
How am I meant to move away from using adaptV4Theme?
The following declaration works when transitioning from mui-v4 to mui-v5:
export const theme = createTheme({
components: { // <------ rename "overrides" to "components"
MUIDataTable: {
styleOverrides: { // <------ put override property INSIDE component definition
paper: {
boxShadow: 'none',
},
responsiveBase: {
overflow: 'clip',
},
},
}.
},
});
See: https://mui.com/customization/theme-components/#global-style-overrides

How do i use custom fonts in navigation tab in react native + expo?

I can load and render custom fonts for text in general, but when i try to specify the font Family for my navigation bar, i get an error: "fontfamily 'poetsenone' is not a system font and has not been loaded through Font.Loadsync.
i've loaded the font in my root comopnent # app.js using Font.Loadasync.
// homescreen.js:
static navigationOptions = {
title: 'Scan',
tabBarOptions: {
labelStyle: {
fontSize: 20,
fontFamily: "poetsenone"
},
tabStyle: {
},
style: {
marginTop: 23,
backgroundColor: '#423D3D',
},
}
};
//app.js
export default class App extends React.Component {
componentDidMount() {
Font.loadAsync({
'poetsenone': require('./assets/fonts/poetsenone.ttf')
});
}
render() {
return (
<AppContainer />
);
}
}
Isn't app.js typically the top-level component? what's going on?
Remove the quotes around 'poetsenone' in loadAsync and it should work.

Best approach for managing strings in react native

I am new in react native. I've been dealing with this big project, that contains too many strings that can be reused many places in the project. So I created a strings.js file , as in android's strings.xml, to store all reusable strings in one file like this,
export const SOME_STRING = 'Some value';
export const ANOTHER_STRING = 'Another value';
...
and imports whenever i needed.
So these are my questions...
1) Is this a good approach ?
2) Is there any alternative to this ?
You don't need to export each value. One better way I know is to export
const SOME_STRING = 'Some value';
const ANOTHER_STRING = 'Another value';
module.exports = {
SOME_STRING:SOME_STRING,
ANOTHER_STRING:ANOTHER_STRING
}
Or you may like to wrap all of this in 1 constant object
const APPLICATION_CONSTANTS = {
SOME_STRING : 'Some string',
ANOTHER_STRING : 'Another string'
}
export default APPLICATION_CONSTANTS;
Usage
import APPLICATION_CONSTANTS from './strings';
APPLICATION_CONSTANTS.SOME_STRING
I am assuming you are using a lot of string because of styling. I do the same thing where I try to extract the maximum amount of styling information to a separate folder with different styling files. Not only variables, but commonly grouped styles as well.
For example:
const styleVariables = {
// Fonts
baseFontSize: 16,
largeFontSize: 24,
// Icons
smallIconSize: 24,
mediumIconSize: 36,
// Colors
mainColor: '#e85e45',
secondaryColor: '#a0c5d8',
offWhite: '#f4f4f4',
darkColor: '#404040',
// Dimensions
headerHeight: 70,
shadowSize: 6
};
export default styleVariables;
And I reference my variables in other styling files where related information is grouped:
/* presentation.js */
import variables from './variables';
export const shadow = {
shadowColor: variables.darkColor,
shadowRadius: variables.shadowSize,
shadowOpacity: 0.35,
shadowOffset: {width: 0, height: 0}
};
export const centered = {
alignItems: 'center'
justifyContent: 'center'
}
And in then in my components I just reference my styles:
import variables from './../styles/variables';
import {centered, shadow} from './../styles/presentation';
class RoundButton extends React.PureComponent {
render() {
return (
<View style={styles.button}>
{this.props.children}
</View>
);
}
}
const styles = StyleSheet.create({
button: {
width: variables.buttonSize,
height: variables.buttonSize,
borderRadius: variables.buttonSize / 2,
...centered
...shadow
}
For text styles and common presentations this really reduces code, and allows for easy modification in just one place.
Simple just you need to create one constantString.js file, and whenever you want to use string from the constantString.js file just import in particular file.
constantString.js
module.exports = {
SOME_STRING : 'Some string',
ANOTHER_STRING : 'Another string'
}
Use string from constantString.js something like,
import constStr from './constantString';
console.log(constStr.SOME_STRING); // Some string
console.log(constStr.ANOTHER_STRING); // Another string
You can use react-intl to play with strings, dates and numbers.
which will provide default functions to handle your data.
import { defineMessages } from 'react-intl';
const messages = defineMessages({
SOME_STRING : 'Some value',
ANOTHER_STRING : 'Another value',
});
export default messages;
learn more about react-intl library

Categories