I am trying to setup global styles in react-native.
I have imported
import {injectGlobal} from 'styled-components';
and have
class XoxoContainer extends Component {
render() {
return <Xoxo {...this.props} />
}
}
injectGlobal`
font-family: '20'
`;
But I keep getting styledComponents.injectGlobals is not a function. in the console.
That function is not part of the library on react-native according to this Github issue. That's why it keeps saying that it's not a function, because it can't find it.
create a styles.js file like this:
import React, {Component} from 'react';
import {
Platform,
StyleSheet
} from 'react-native';
export const styles = StyleSheet.create({
view_flex_one_white: {
flex: 1,
backgroundColor: white
}});
and use this anywhere in your app with import
import {styles} from "...link to file/styles";
render(){
return(
<View style={styles.view_flex_one_white}>
</View>
)
}
Create a js file with this pattern:
'use strict';
var React = require('react-native');
var myStyle = React.StyleSheet.create({
style1: { },
style2: { }
)}
module.exports = myStyle;
your component js use require to use that style sheet
var customStyle = require('../the/path/to/commonStyleSheet');
Use now like this:
<View style = {customStyle .style1} />
Related
I'm new to react native and I'm following a tutorial to learn the language.
I'm now trying to set a background image using ImageBackground.
WelcomeScreen.js:
import React from 'react';
import { ImageBackground, StyleSheet } from 'react-native-web';
function WelcomeScreen(props) {
return (
<ImageBackground
style={styles.background}
source={require("../assets/background.jpg")}
></ImageBackground>
);
}
const styles = StyleSheet.create({
background: {
flex: 1
}
})
export default WelcomeScreen;
App.js
import React from 'react';
import { View } from 'react-native';
import WelcomeScreen from './app/screens/WelcomeScreen';
export default function App() {
return (
<WelcomeScreen />
);
}
Now I get this error: Error: Image: asset with ID "1" could not be found. Please check the image source or packager.
I have a app folder in in my projectfolder. In this app folder I have the assets folder and a screens folder. The WelcomeScreen.js is in the screens folder. The background.jpg is in the assets folder and the App.js is in the main/project folder.
I can't seem to find any way to fix this error.
Try changing your module import from react-native-web to just react-native
WelcomeScreen.js
import React from "react";
import { ImageBackground, StyleSheet } from "react-native";
function WelcomeScreen(props) {
return (
<ImageBackground
style={styles.background}
source={require("../assets/background.png")}
></ImageBackground>
);
}
const styles = StyleSheet.create({
background: {
flex: 1,
},
});
export default WelcomeScreen;
You do not need to add ./app to your WelcomeScreen.js file path
App.js
import WelcomeScreen from "./screens/WelcomeScreen";
export default function App() {
return <WelcomeScreen />;
}
Hope this helps!
I'm trying to pass my theme object to styled-components on my Next.js project, but it keep's failing to receive it as a props.
That's my _document.tsx
import { getInitialProps } from "#expo/next-adapter/document";
import Document, { DocumentContext, DocumentInitialProps } from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
const initialProps = await getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
}
After that I wrapped my _app.tsx with the ThemeProvider
import Layout from '../components/Layout'
import 'setimmediate';
import { ThemeProvider } from 'styled-components';
import { wrapperStore } from "../store";
import { ApolloProvider } from "#apollo/client";
import client from './api/apollo-client';
import React from 'react';
import lightTheme from '../helpers/light-mode';
import { AppProps } from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
return (
<React.Fragment>
<ApolloProvider client={client}>
<ThemeProvider theme={lightTheme}>
<Layout>
<Component {...pageProps} />
</Layout>
</ThemeProvider>
</ApolloProvider>
</React.Fragment>
)
}
export default wrapperStore.withRedux(MyApp);
From here I receive a warning when I try to wrap my component, exporting it withTheme
[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class "Connect(Front)"
when I try to console log theme from my props, it returns undefined, and when I create a styled component, trying to use theme as props it causes an error
export const RecruitmentTextLocation = styled.Text`
fontSize: ${scaleFont(15)};
textAlign: left;
marginTop: ${scale(5)}px;
marginBottom: ${scale(1)}px;
fontFamily: roboto;
fontWeight: 500;
color: ${({theme}) => theme.colors.cardTitleColor};
`;
TypeError: Cannot read property 'colors' of undefined
I'm really stuck on how I can use theming with styled-components on Nextjs.
I suppose you problem is in light-mode.tsx. How can i see you use typescript in that case need create a declarations file and DefaultTheme interface. example
Create a declarations file
TypeScript definitions for styled-components can be extended by using declaration merging since version v4.1.4 of the definitions. documentation
light-mode.tsx
import { DefaultTheme } from 'styled-components';
export const lightTheme: DefaultTheme = {
colors: {
cardTitleColor: red;
}
};
I was looking for the same and found a solution for typing the theme object you receive as prop on your styled components.
First, export the types of your themes, e.g.:
export type LightTheme = typeof lightTheme;
Then add a src/declaration.d.ts file with the below, so to enhance the DefaultTheme exported by styled-components to be typed with your custom theme object:
import { Theme } from "globalStyles";
declare module "styled-components" {
export interface DefaultTheme extends Theme {}
}
From there you won't need any withTheme to use your theme object, as you will simply be able to access it through:
color: ${({theme}) => theme.colors.cardTitleColor};
I couldn't find the current method for achieving this. It used to be:
'use strict';
var React = require('react-native');
var { StyleSheet } = React;
module.exports = StyleSheet.create({
});
In a separate file and then you would require it as follows:
var styles = require('./styles');
But that no longer seems to work?
in styles.js file, you can do
import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
});
export default styles;
and in other files
import styles from './styles';
You can just do the following:
Style.js
import { StyleSheet } from 'react-native';
export default Style = StyleSheet.create({
// your styles here
container: {
flex: 1
}
});
And then you import your StyleSheet with:
import Style from 'PATH_TO_STYLE.js';
and then you can use it with:
<View style={Style.container} />
I want to make 2 variables for the main colors which can be used on the whole app. Here is the code:
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
const primary = '#27bcb5';
const secondary = '#ffffff;
How can I export these 2 variables together for using on the app components?
Issue with the solution is :
import {DefaultStyle} from './variables';
const screenHeight = Dimensions.get("window").height;
const styles = {
wrapper: {},
slide1: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: primary,
it says can't find variable primary
You can export them with:
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
const primary = '#27bcb5';
const secondary = '#ffffff';
export const DefaultStyle = {
primary,
secondary,
}
So you can use them as:
import { DefaultStyle } from './default-variables';
console.log(DefaultStyle.primary);
console.log(DefaultStyle.secondary);
You could do a named export. E.g. :
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
const primary = '#27bcb5';
const secondary = '#ffffff';
export { primary, secondary };
After that, you can import your styles via:
import { primary, secondary } from 'YOUR_FILE_PATH'
// Declarations of colors variables
const Maincolor ="#333640"
const Backgroundcolor = "#FFFFFF"
const Gridcolor = "#A7A9AB"
const colors = // Made to be bind in one because only one export is possiable
{
Maincolor,
Backgroundcolor,
Gridcolor,
}
export default colors; // exporting as default
// And in your main code where you have to include
import colors from 'path_of_the_file'
// then in styles use
style ={{backgroundColor:color.Maincolor}} // example how to use
I like to do something better, define a global file where you can save like Moment() time, Device Measures, etc.
global.js
const global = {
PRIMARY: '#27bcb5',
SECONDARY: '#ffffff,
DEVICE_MEASURES:{
WIDTH: Dimensions.get("window").width,
HEIGHT: Dimensions.get("window").height;
},
...
}
export default global
And then in your code:
import GLOBAL from '(directory)/global'
<View style={{ width: GLOBAL.DEVICE_MEASURES.WIDTH }}>
<Text style={{ color: GLOBAL.PRIMARY }}>
sup
</Text>
</View>
It's just better to have a global file where you can store all your app's configurations.
I am trying to implement navigation drawer on click of menu icon in toolbar, i am trying this from many days but i could not find any good resource online,I have followed some stack overflow answer and implemented this till now:
MyToolbar.js
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text
} from 'react-native';
var ToolbarAndroid = require('ToolbarAndroid');
export default class MyToolbar extends Component {
render() {
// var navigator = this.props.navigator;
return (
<ToolbarAndroid
title={this.props.title}
navIcon={require('./ic_menu.png')}
style = {styles.toolbar}
titleColor={'white'}
onIconClicked={this.props.sidebarRef}/>
);
}
}
const styles = StyleSheet.create({
toolbar: {
height: 56,
backgroundColor: '#08AE9E',
width: 370,
alignItems: 'center'
}
});
openDrawerFromToolbar.js
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
DrawerLayoutAndroid,
ScrollView,
} from 'react-native';
var ToolbarAndroid = require('ToolbarAndroid');
var MyToolbar = require('./MyToolbar');
export default class OpenDrawerFromToolbar extends Component {
render() {
var navigationView = (
<ScrollView>
<View style = {{height:100, backgroundColor:'blue', justifyContent:'center'}}>
<Text style = {{height:25, color:'white', fontSize:25, marginLeft:20}}>Welcome To ReactNative</Text>
</View>
// <ListView></ListView>
//render your list items
</ScrollView>
);
return (
<DrawerLayoutAndroid
drawerWidth={300}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}
ref={'DRAWER'}>
<MyToolbar style={styles.toolbar}
title={'Calendar'}
sidebarRef={()=>this._setDrawer()}/>
</DrawerLayoutAndroid>
);
}
_setDrawer() {
this.refs['DRAWER'].openDrawer();
}
}
const styles = StyleSheet.create({
//your own style implementation
});
index.android.js
import React, { Component } from 'react';
import {
AppRegistry
} from 'react-native';
var OpenDrawerFromToolbar = require('./components/OpenDrawerFromToolbar');
class NewsTrack extends Component {
render() {
return (
<OpenDrawerFromToolbar
/>
);
}
}
AppRegistry.registerComponent('NewsTrack', () => NewsTrack);
Initially clicking on toolbar was not doing any action and navigation drawer was not opening now I'm getting blank screen. what am i missing in the code?
Edit : I have updated the code and now i am facing this error: "Element type is invalid: expected a string(for built-in components)or a class/function (for composite components) but got: object.
I have checked other such question they say some import or export is wrong i am not able to find out which in my case is wrong, can someone please help?
You can use Drawer provided by native base . It comes with toolbar functionality and very easy to use. I am using it in one of my projects.
https://docs.nativebase.io/Components.html#Drawer