I'm trying to switch this line of code to an arrow function:
<NavigationContainer theme={theme == 'Amber' ? Amber : Tiger}
<NavigationContainer theme={() => {
if (theme == 'Amber') {
return Amber;
} else {
return Tiger;
}
}}>
But for some reason when I perform this change, I get this error: TypeError: undefined is not an object (evaluating 'colors.background')
What's the problem here?
Thanks
Full code for reference:
import React, { useState } from 'react';
import { NavigationContainer, useTheme } from '#react-navigation/native';
import { StatusBar } from 'expo-status-bar';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import * as NavigationBar from "expo-navigation-bar";
import Ionicons from 'react-native-vector-icons/Ionicons';
import CounterScreen from './screens/CounterScreen';
import CustomizeScreen from './screens/CustomizeScreen';
import SettingsScreen from './screens/SettingsScreen';
import MedalsScreen from './screens/MedalsScreen.js';
import { Amber, Tiger } from "../styles/Themes"
import { ThemeContext } from '#rneui/themed';
const counterName = 'Counter';
const customizeName = 'Customize';
const settingsName = 'Settings';
const medalsName = "Medals";
const Tab = createBottomTabNavigator();
NavigationBar.setBackgroundColorAsync("#212121");
export default function MainContainer() {
const [theme, setTheme] = useState('Amber');
const themeData = { theme, setTheme };
return (
<ThemeContext.Provider value={themeData}>
<NavigationContainer theme={() => {
if (theme == 'Amber') {
return Amber;
} else {
return Tiger;
}
}}>
<StatusBar style="auto" />
<Tab.Navigator
initialRouteName={counterName}
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
let rn = route.name;
if (rn === counterName) {
iconName = focused ? 'radio-button-on-outline' : 'radio-button-off-outline';
} else if (rn === customizeName) {
iconName = focused ? 'color-palette' : 'color-palette-outline';
} else if (rn === medalsName) {
iconName = focused ? 'medal' : 'medal-outline';
} else if (rn === settingsName) {
iconName = focused ? 'settings' : 'settings-outline';
}
return <Ionicons name={iconName} size={size} color={color} />
},
tabBarInactiveTintColor: '#aaaaaa',
tabBarLabelStyle: { paddingBottom: 10, fontSize: 10 },
tabBarStyle: { padding: 10, height: 70, borderTopWidth: 1 },
headerStyle: { borderBottomWidth: 1 },
headerTitleAlign: 'center',
headerTitleStyle: { fontSize: 20 },
})}>
<Tab.Screen name={counterName} component={CounterScreen} />
<Tab.Screen name={customizeName} component={CustomizeScreen} />
<Tab.Screen name={medalsName} component={MedalsScreen} />
<Tab.Screen name={settingsName} component={SettingsScreen} />
</Tab.Navigator>
</NavigationContainer>
</ThemeContext.Provider>
);
}
Themes.js
const Amber = {
dark: true,
colors: {
primary: '#FFBF00',
background: '#212121',
card: '#212121',
text: '#FFBF00',
border: '#FFBF00',
notification: '#FFBF00',
},
};
const Tiger = {
dark: true,
colors: {
primary: '#F96815',
background: '#212121',
card: '#212121',
text: '#F96815',
border: '#F96815',
notification: '#F96815',
},
};
export { Amber, Tiger }
looks like its expecting an object, why not try using useMemo or a simple function the generated an object before setting the proprty
const containerTheme = useMemo(() => {
// logic to select theme
if (theme == 'Amber') {
return Amber;
} else {
return Tiger;
}
}, [theme])
<NavigationContainer theme={containerTheme}>
// simple function
const getTheme = () => {
// logic to select theme
if (theme == 'Amber') {
return Amber;
} else {
return Tiger;
}
}
const containerTheme = getTheme();
if your function is expensive check the time
console.time('get theme');
const containerTheme = getTheme();
console.timeEnd('get theme');
Related
I'm trying to apply the theme the user chose to the initial value of useState(), but when I refresh the page, the choice does not apply. What do I have to change in order for the value to persist through page refreshing?
theme-toggler.js
import React, { createContext, useState } from "react";
export const themes = {
light: {
background: "#41A9EC",
fontColor: '#FFF'
},
dark: {
background: "#F9F9",
fontColor: '#000'
}
}
export const ThemeContext = createContext({})
export const ThemeProvider = (props) => {
const [theme, setTheme] = useState(localStorage.themes)
if(theme === themes.light) {
localStorage.setItem('themes', JSON.stringify(themes.light))
}
if(theme === themes.dark) {
localStorage.setItem('themes', JSON.stringify(themes.dark))
}
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{props.children}
</ThemeContext.Provider>
)
}
theme-toggler-button.js
import React, { useContext } from "react"
import { ThemeContext, themes } from "../../context/theme-toggler"
import { Button } from "../button/button"
export const ThemeTogglerButton = () => {
const { theme, setTheme } = useContext(ThemeContext)
return (
<div style={{ backgroundColor: theme.background, color: theme.fontColor }}>
<Button onClick={() => setTheme(theme === themes.light ? themes.dark : themes.light)}>Theme Toggler</Button>
</div>
)
}
Thanks in advance.
import React, { createContext, useState } from "react";
export const themes = {
light: {
background: "#41A9EC",
fontColor: '#FFF'
},
dark: {
background: "#F9F9",
fontColor: '#000'
}
}
export const ThemeContext = createContext({})
export const ThemeProvider = (props) => {
const [theme, setTheme] = useState(localStorage.getItem("themes"))
useEffect(() => {
if(theme === themes.light) {
localStorage.setItem('themes', JSON.stringify(themes.light))
}
if(theme === themes.dark) {
localStorage.setItem('themes', JSON.stringify(themes.dark))
}
},[theme])
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{props.children}
</ThemeContext.Provider>
)
}
After a few days, I was able to make it work. I'm posting the solution I found, in order to help others with similar problems.
theme-toggler-button file:
import React, { useContext } from "react"
import { ThemeContext, themes } from "../../context/theme-toggler"
import { Button } from "../button"
export const ThemeTogglerButton = () => {
const { theme, setTheme } = useContext(ThemeContext)
function handleClick() {
const localTheme = JSON.parse(localStorage.getItem("themes"))
console.log(localTheme)
setTheme(theme === themes.light ? themes.dark : themes.light)
if (localTheme) {
localStorage.setItem('themes', JSON.stringify(localTheme.name === 'light mode' ? themes.dark : themes.light))
} else {
localStorage.setItem('themes', JSON.stringify(themes.light))
}
}
return (
<Button style={{ backgroundColor: theme.background,
color: theme.fontColor }}
onClick={() => handleClick()}>{
(theme === themes.light ?
themes.dark.name : themes.light.name)}
</Button>
)
}
theme-toggler file:
import React, { createContext, useState, useEffect } from "react";
export const themes = {
light: {
name: 'light mode',
background: '#41A9EC',
fontColor: '#FFF'
},
dark: {
name: 'dark mode',
background: '#212121',
fontColor: '#AAB0BC'
}
}
export const ThemeContext = createContext({})
export const ThemeProvider = (props) => {
const [theme, setTheme] = useState([])
useEffect(() => {
const localTheme = JSON.parse(localStorage.getItem("themes"))
if (!localTheme) {
localStorage.setItem('themes', JSON.stringify(themes.light))
setTheme(themes.light)
}
if (localTheme) {
if (localTheme.name === 'light mode') {
localStorage.setItem('themes', JSON.stringify(themes.light))
setTheme(themes.light)
}
if (localTheme.name === 'dark mode') {
localStorage.setItem('themes', JSON.stringify(themes.dark))
setTheme(themes.dark)
}
}
}, [])
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{props.children}
</ThemeContext.Provider>
)
}
Please find below my project repository, where I'm currently using the solution above: https://github.com/Alex-Lima84/pokemon-react-api
Im using Material UI's Button component and would like to conditionally determine the variant of the button. That is, on screens medium and up, the variant should be 'outlined' and when the screen is smaller than medium, the variant type should be none. I am using a class component. I have done my research to see what others have done. I have seen the method of using useMediaQuery method but that would require me to change the component to a functional component. Im not sure if I know if that is a good idea because the component is rather a large one and that means will be a bit confusing to convert. I also tried using a ternary operator like this:
const variantType = theme.breakpoints.down("md") ? '' : 'outline';
<Button variant={variantType}>
Food Pick
</Button>
But this didnt do the job. Is there any other way to accomplish this?
Update: Here is my code after trying to wrap the component but in a functional component but its giving an error:
import { withStyles, withTheme, useTheme } from '#material-ui/core';
import PropTypes from 'prop-types';
import Button from '#material-ui/core/Button';
import Typography from '#material-ui/core/Typography';
import Grid from '#material-ui/core/Grid';
import { PulseLoader } from 'react-spinners';
import Icon from '#material-ui/core/Icon';
import Chip from '#material-ui/core/Chip';
import useMediaQuery from '#material-ui/core/useMediaQuery';
const styles = theme => ({
beta: {
height: '17px',
fontSize: '12px',
marginLeft: '10px'
},
scrollContainer: {
flex: 1,
maxHeight: '400px',
minHeight: '300px',
overflowY: 'auto'
},
progressContainer: {
height: '350px',
},
modalDescription: {
color: theme.palette.text.secondary,
marginTop: '20px',
},
button: {
marginTop: '20px',
marginLeft: '10px',
marginRight: '10px',
},
smartSuggestContainer: {
textAlign: 'right',
paddingRight: '35px',
[theme.breakpoints.down('xs')]: {
display: 'flex',
justifyContent: 'center',
flexDirection: 'row',
margin: '40px 0'
},
},
});
export default function MyComponentWrapper({ ...rest }) {
const theme = useTheme();
const mediumScreen = useMediaQuery(theme.breakpoints.down('md'));
return <FoodDescriptions {...rest} mediumScreen={mediumScreen} />;
}
class FoodDescriptions extends Component {
static PAGE_SIZE = 25;
constructor(props) {
super(props);
this.state = {
showFoodDescriptionsModal: false,
dataLoaded: false,
data: [],
page: 0,
sortBy: 'return',
sortDir: 'desc',
};
}
componentDidMount() {
document.addEventListener('keydown', this.handleKeypress);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeypress);
}
fetchData = async (page, sortBy, sortDir) => {
const { currentBotId } = this.props;
const offset = page * FoodDescriptions.PAGE_SIZE;
const data = await getFoodDescriptions(currentBotId, sortBy, sortDir, FoodDescriptions.PAGE_SIZE, offset);
this.setState({
dataLoaded: true,
data,
});
};
handleKeypress = (e) => {
const { showSnartConfigsModal } = this.state;
const { key } = e;
if (key === 'Escape' && showSnartConfigsModal) {
this.closeModal();
}
};
applyConfig = (botId, params) => {
const { updateConfig, botConfig, actions } = this.props;
updateConfig({ name: botConfig.name, config: Object.assign(botConfig.config, params) });
this.closeModal();
actions.showNotification({ data: 'Configuration has been applied' });
};
openModal = () => {
const { page, sortBy, sortDir } = this.state;
this.fetchData(page, sortBy, sortDir);
this.setState({
showFoodDescriptionsModal: true,
});
};
closeModal = () => {
this.setState({
showFoodDescriptionsModal: false,
});
};
changePage = (page) => {
const { sortBy, sortDir } = this.state;
this.setState({
page,
dataLoaded: false
}, () => this.fetchData(page, sortBy, sortDir));
};
changeSortBy = (sortBy) => {
/* eslint-disable-next-line prefer-destructuring */
let sortDir = this.state.sortDir;
if (sortBy === this.state.sortBy) {
sortDir = (this.state.sortDir === 'desc') ? 'asc' : 'desc';
}
this.setState({
sortBy,
sortDir,
dataLoaded: false,
}, () => this.fetchData(this.state.page, sortBy, sortDir));
};
renderEmptyState() {
const { classes } = this.props;
return (
<Grid container alignItems="center" justify="center" className={classes.progressContainer}>
<Typography className={classes.noCoinsText}>No configurations found</Typography>
</Grid>
);
}
renderLoader() {
const { classes } = this.props;
return (
<Grid container alignItems="center" justify="center" className={classes.progressContainer}>
<PulseLoader size={6} color="#52B0B0" loading />
</Grid>
);
}
renderTable() {
const { data, page } = this.state;
return (
<StrategiesTable
strategies={data}
onClickCopy={this.applyConfig}
page={page}
changePage={this.changePage}
sortBy={this.changeSortBy} />
);
}
render() {
const {
classes, userFeatures, botConfig, theme
} = this.props;
const { showFoodDescriptionsModal, dataLoaded } = this.state;
if (!botConfig) {
return null;
}
return (
<Fragment>
<div className={classes.smartSuggestContainer}>
<Button
name="discoverConfigs"
variant={theme.breakpoints.down(600) ? '' : 'outlined'}
color="primary"
size="small"
disabled={!userFeatures['smart_suggest_backtests'.toUpperCase()] || botConfig.status.toLowerCase() === STATUSES.RUNNING}
onClick={this.openModal}>
Food Buy
</Button>
</div>
</Fragment>
);
}
}
function mapStateToProps(state) {
return {
userFeatures: state.global.paywall.features,
};
}
function mapDispatchToProps(dispatcher) {
return {
actions: {
...bindActionCreators({
showNotification,
}, dispatcher)
}
};
}
connect(mapStateToProps, mapDispatchToProps)(withTheme()(withStyles(styles)(FoodDescriptions)));
Why don't you just create a functional component using useMediaQuery and returning the responsive Button ?
my code works but for some reason, I get this warning:
"Warning: Cannot update a component from inside the function body of a different component."
I think it is something to do with these lines (whan i add them i get the error):
const product = state.data.find((data) => data._id === id);
useEffect(() => {
if ((product.moistureSensor.tests !== undefined) || (product.lightSensor.tests !== undefined)) {
setDataState({ 'lightSensor': product.lightSensor.tests[product.lightSensor.tests.length - 1].status, 'muisterSensor': product.moistureSensor.tests[product.moistureSensor.tests.length - 1].status });
console.log(stateData);
}
}, []);
there is probably something logical in react that I don't understand.
this is the full code -
import React, { useContext, useEffect, useState, useRef } from 'react';
import {
Text,
StyleSheet,
Switch,
Button,
TouchableOpacity, SafeAreaView, View, ActivityIndicator
} from 'react-native';
import { client } from '../../api/SocketConfig'
import { NavigationEvents } from 'react-navigation';
import { Context as ProductDataContext } from '../../context/ProductDetailContext'
import DynamicProgressCircle from '../../components/DynamicProgressCircle';
const SensorDataShow = ({ id }) => {
const { state } = useContext(ProductDataContext);
const [isEnabled, setIsEnabled] = useState(false);
const [loading, setLoading] = useState(false);
const [stateData, setDataState] = useState({ 'lightSensor': null, 'muisterSensor': null });
const listener = (dataServer) => {
console.log(`the data from server:${dataServer}`);
if (dataServer.lightSensor !== null)
setDataState({ 'lightSensor': dataServer.lightSensor, 'muisterSensor': dataServer.muisterSensor });
setLoading(false)
}
const changeData = () => { client.on("showData", listener) }
const emitGetData = () => { client.emit("GetData", id) }
let timer = useRef(null);
useEffect(() => {
if (loading === true) {
console.log('timeout started')
timer.current = setTimeout(() => {
setLoading(false)
console.log('i am after timeout');
}, 35000);
} return () => clearTimeout(timer.current);
}, [loading]);
const product = state.data.find((data) => data._id === id);
useEffect(() => {
if ((product.moistureSensor.tests !== undefined) || (product.lightSensor.tests !== undefined)) {
setDataState({ 'lightSensor': product.lightSensor.tests[product.lightSensor.tests.length - 1].status, 'muisterSensor': product.moistureSensor.tests[product.moistureSensor.tests.length - 1].status });
console.log(stateData);
}
}, []);
useEffect(() => {
changeData();
return () => {
client.removeAllListeners('showData', listener);
}
}, []);
return (
<>
{stateData.muisterSensor !== null && (
<>
<Text style={{ fontSize: 28 }}>Moister sensor data:</Text>
<DynamicProgressCircle
changingValues={{
Percent: parseInt(
stateData.muisterSensor
),
}}
/>
</>
)}
{stateData.lightSensor !== null && (
<Text style={{ fontSize: 28 }}>
Light sensor data:
{
stateData.lightSensor
}
</Text>
)}
{loading === false ?
<Button
title="Get Data"
style={styles.button}
onPress={() => {
emitGetData(id), setLoading(true)
}}
/>
: <ActivityIndicator animating={true} size="large" color="red" />}
</>
);
};
const styles = StyleSheet.create({
button: {
alignItems: 'center',
backgroundColor: '#00CC00',
padding: 10,
marginTop: 10,
},
buttonON: {
alignItems: 'center',
backgroundColor: '#00CC00',
padding: 10,
marginTop: 10,
},
buttonOFF: {
alignItems: 'center',
backgroundColor: '#DB2828',
padding: 10,
marginTop: 10,
},
buttonNotOnline: {
alignItems: 'center',
backgroundColor: '#9B9D9A',
padding: 10,
marginTop: 10,
},
switch: {
alignItems: 'center',
},
});
export default SensorDataShow;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I appreciate any help I can get !
Error is:
Invariant Violation: View config getter callback for component 'H' must be a function (received undefined)
I'm using react-native to make application and error happens when I clicked login button in MainLogin.js file. (It has to move to mainpage when clicking login button in login page)
I searched a lot but cannot know what is component 'H'.
attatched index.js (src/screens/index.js) and MainLogin.js (src/screens/MainLogin.js)
<index.js>
import React from 'react';
import {
Text
} from 'react-native';
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import { createBottomTabNavigator } from "react-navigation-tabs";
import LoginScreen from './MainLogin';
import HomeScreen from './MainPage';
import DiaryScreen from './Diarymemo';
import StatScreen from './MoodStatistics';
import CommuScreen from './Community';
import StoreScreen from './Store';
const HomeStack = createStackNavigator(
{
HomeScreen
},
{ defaultNavigationOptions : ({navigation}) => ({
title: 'Home'}),
}
);
const DiaryStack = createStackNavigator(
{
DiaryScreen
},
{ defaultNavigationOptions : ({navigation}) => ({
title: 'Diary'}),
}
);
const StatStack = createStackNavigator(
{
StatScreen
},
{ defaultNavigationOptions : ({navigation}) => ({
title: 'Stat'}),
}
);
const CommunityStack = createStackNavigator(
{
CommuScreen
},
{ defaultNavigationOptions : ({navigation}) => ({
title: 'Network'}),
}
);
const StoreStack = createStackNavigator(
{
StoreScreen
},
{ defaultNavigationOptions : ({navigation}) => ({
title: 'Store'}),
}
);
const TabNavigator = createBottomTabNavigator(
InitialRouteName = 'Home',
{
Diary: DiaryStack,
Stat: StatStack,
Home: HomeStack,
Network: CommunityStack,
Store: StoreStack,
},
{
defaultNavigationOptions: ({navigation}) => ({
tabBarIcon: ({focused, horizontal, tintColor}) => {
const {routeName} = navigation.state;
let icon = "▲";
if(routeName === 'Diary'){
icon = "📓";
} else if(routeName === 'Stat'){
icon = "📊"
} else if(routeName === 'Home'){
icon = "🍎"
} else if(routeName === 'Network'){
icon = "👫"
} else if(routeName === 'Store'){
icon = "🛍"
}
// can use react-native-vector-icons
// <Icon name={iconName} size={iconSize} color={iconColor} />
return <Text style={{color: focused && "#46c3ad" || "#888"}}>{icon}</Text>
}
}),
lazy: false,
tabBarOptions: {
activeTintColor: "#46c3ad",
inactiveTintColor: "#888",
},
}
);
const AppStack = createStackNavigator(
{
LoginScreen: LoginScreen,
TabNavigator: {
screen: TabNavigator,
navigationOptions: ({navigation}) => ({
headerShown: false,
}),
},
}
);
export default createAppContainer(AppStack);
<MainLogin.js>
import React, {Component} from 'react';
import {
View,
Text,
TextInput,
TouchableOpacity,
StyleSheet
} from 'react-native';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
export default class LoginScreen extends Component{
static navigationOptions = {
headerShown: false,
};
_doLogin(){
// do something
this.props.navigation.replace('TabNavigator')
}
render(){
return (
<View style={styles.container}>
<View style={styles.titleArea}>
<Text style={styles.title}>MoodiBuddy</Text>
</View>
<View style={styles.formArea}>
<TextInput
style={styles.textForm}
placeholder={"ID"}/>
<TextInput
style={styles.textForm}
placeholder={"Password"}/>
</View>
<View style={styles.buttonArea}>
<TouchableOpacity
style={styles.button}
onPress={this._doLogin.bind(this)}>
<Text style={styles.buttonTitle}>Login</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
paddingLeft: wp('10%'),
paddingRight: wp('10%'),
justifyContent: 'center',
},
titleArea: {
width: '100%',
padding: wp('10%'),
alignItems: 'center',
},
title: {
fontSize: wp('10%'),
},
formArea: {
width: '100%',
paddingBottom: wp('10%'),
},
textForm: {
borderWidth: 0.5,
borderColor: '#888',
width: '100%',
height: hp('5%'),
paddingLeft: 5,
paddingRight: 5,
marginBottom: 5,
},
buttonArea: {
width: '100%',
height: hp('5%'),
},
button: {
backgroundColor: "#46c3ad",
width: "100%",
height: "100%",
justifyContent: 'center',
alignItems: 'center',
},
buttonTitle: {
color: 'white',
},
})
I am new in React Native, I am working on an app where I had to add a prefabricated header, which brings a button to which I want to set the option to go back with the function goBack of Navigation, however the button does not Nothing, also I tried with Navigation.navigate ('route'), but the issue continues. I would really appreciate it if you can help with this.
The code:
import { NavigationContainer, useNavigationState} from '#react-navigation/native';
import { NavigationActions } from 'react-navigation';
import { createStackNavigator } from '#react-navigation/stack';
import { Toolbar } from 'react-native-material-ui';
import * as React from 'react';
import { Platform, StatusBar, StyleSheet, View, Text } from 'react-native';
import BottomTabNavigator from '../../navigation/BottomTabNavigator';
import LinkingConfiguration from '../../navigation/LinkingConfiguration';
import CatHome from '../../screens/subScreens/CatHome';
const Stack = createStackNavigator();
export default function Navigator({navigation}) {
const SearchBar= ()=>{
//const { navigate } = this.props.navigation;
return(
<Toolbar
leftElement= {backOption()}
onLeftElementPress= {()=>navigation.goBack()}
//isSearchActive= {true}
style={{
container: styles.searchBar,
}}
centerElement="DIRECTAPP"
searchable={{
autoFocus: true,
placeholder: 'Buscar',
}}
rightElement={{
menu: {
icon: "more-vert",
iconProps : {
size: 30,
color: 'gray',
},
labels: ["Locación", "Contáctanos"]
}
}}
onRightElementPress={ (label) => { console.log(label) }}
/>
);
}
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="dark-content" />}
<NavigationContainer linking={LinkingConfiguration}>
<Stack.Navigator screenOptions={{
headerLeft: null,
headerTitle: props => <SearchBar {...props} />,
headerStyle: {
backgroundColor: '#9acd32',
}
}}>
<Stack.Screen name="Root" component={BottomTabNavigator} />
<Stack.Screen name="CatHome" component={CatHome} />
</Stack.Navigator>
</NavigationContainer>
</View>
);
}
function backOption (){
//const Route=useRoute();
const state = useNavigationState(state => state);
const routeName = (state.routeNames[state.index]);
//console.log(routeName);
if (routeName=='Root') {
return ''
}
else {
return 'arrow-back'
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
searchBar: {
backgroundColor: '#9acd32',
width: '100%',
shadowOffset: { width: 1, height: 13},
shadowOpacity: 0.1,
}
});
Here is the new code:
import { NavigationContainer, useNavigationState, useNavigation } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { Toolbar } from 'react-native-material-ui';
import * as React from 'react';
import { Platform, StatusBar, StyleSheet, View, Text } from 'react-native';
import BottomTabNavigator from '../../navigation/BottomTabNavigator';
import LinkingConfiguration from '../../navigation/LinkingConfiguration';
import CatHome from '../../screens/subScreens/CatHome';
const Stack = createStackNavigator();
export default function Navigator() {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="dark-content" />}
<NavigationContainer linking={LinkingConfiguration}>
<Stack.Navigator screenOptions={{
headerLeft: null,
headerTitle: props => <SearchBar {...props} />,
headerStyle: {
backgroundColor: '#9acd32',
}
}}>
<Stack.Screen name="Root" component={BottomTabNavigator} />
<Stack.Screen name="CatHome" component={CatHome} />
</Stack.Navigator>
</NavigationContainer>
</View>
);
}
function SearchBar (){
const navigation = useNavigation();
//const { navigate } = this.props.navigation;
return(
<Toolbar
leftElement= {backOption()}
onLeftElementPress= {()=>navigation.goBack()}
//isSearchActive= {true}
style={{
container: styles.searchBar,
}}
centerElement="DIRECTAPP"
searchable={{
autoFocus: true,
placeholder: 'Buscar',
}}
rightElement={{
menu: {
icon: "more-vert",
iconProps : {
size: 30,
color: 'gray',
},
labels: ["Locación", "Contáctanos"]
}
}}
onRightElementPress={ (label) => { console.log(label) }}
/>
);
}
function backOption (){
//const Route=useRoute();
const state = useNavigationState(state => state);
const routeName = (state.routeNames[state.index]);
//console.log(routeName);
if (routeName=='Root') {
return ''
}
else {
return 'arrow-back'
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
searchBar: {
backgroundColor: '#9acd32',
width: '100%',
shadowOffset: { width: 1, height: 13},
shadowOpacity: 0.1,
}
});