ReferenceError: Can't find variable: SearchBar in React Native - react-native

I got an error called "ReferenceError: Can't find variable: SearchBar". I tried to check for syntax error and run the app again. But the same error appeared. How can I rectify it? Thanks.
This is my SearchScreen.js file.
import React, { useState } from 'react';
import { StyleSheet, View, TextInput } from 'react-native';
const SearchScreen = () => {
const [term, setTerm] = useState('')
return (
<View>
<SearchBar
term={term}
onTermChange={(newTerm) => setTerm(newTerm)} />
</View>
);
}
const styles = StyleSheet.create({});
export default SearchScreen;
This is my SearchBar.js file.
import React from 'react';
import { StyleSheet, View, TextInput } from 'react-native';
import { EvilIcons } from '#expo/vector-icons'
const SearchBar = ({ term, onTermChange }) => {
return (
<View style = {styles.background}>
<EvilIcons style={styles.icon} name="search" />
<TextInput
value={term}
style={styles.input}
placeholder="Search"
onChangeText={newTerm => onTermChange(newTerm)} />
</View>
);
}
const styles = StyleSheet.create({
background: {
height: 50,
borderRadius: 6,
marginHorizontal: 15,
flexDirection: 'row',
alignItems: 'center'
},
input: {
flex: 1
},
icon: {
fontSize: 35,
alignSelf: 'center',
marginHorizontal: 15
}
});

Related

React Native Snap Carousel Functional Component Issue

I'm using this snack as a template for implementing my own carousel component. This template is using Class Component and I converted it to a Functional component
https://snack.expo.io/#bd-arc/react-native-snap-carousel-%7C-example-with-custom-interpolations
I added this to my project and I believe some error is happening when rendering the Carousel but I'm unable to tell. It renders - but not all the components are rendering. I have only changed the Carousel itself to a function component. The problem is the is not showing below the Carousel - also if I add multiple VideoCarousel's, only the first one displays.
My code is below
App.js
import React from 'react';
import { View } from 'react-native';
import Header from './components/header';
import VideoCarousel from './components/videoCarousel';
import tailwind from 'tailwind-rn';
const App = () => {
return (
<View style={tailwind('flex pt-12 items-center bg-gray-300 h-full')}>
<Header />
<VideoCarousel />
<VideoCarousel />
</View>
)
};
export default App;
VideoCarousel.js
import React, { useState } from 'react';
import { Text, View, Dimensions, StyleSheet, Alert } from 'react-native';
import Carousel from 'react-native-snap-carousel'; // Version can be specified in package.json
import { scrollInterpolator, animatedStyles } from './../utils/animations';
const SLIDER_WIDTH = Dimensions.get('window').width;
const ITEM_WIDTH = Math.round(SLIDER_WIDTH * 0.7);
const ITEM_HEIGHT = Math.round(ITEM_WIDTH * 3 / 4);
const DATA = [];
for (let i = 0; i < 10; i++) {
DATA.push(i)
}
const VideoCarousel = () => {
const [index, setIndex] = useState(0);
_renderItem = (index) => {
return (
<View style={styles.itemContainer}>
<Text style={styles.itemLabel}>{`Item ${index.index}`}</Text>
</View>
);
}
return (
<View>
<Carousel
data={DATA}
renderItem={this._renderItem}
sliderWidth={SLIDER_WIDTH}
itemWidth={ITEM_WIDTH}
containerCustomStyle={styles.carouselContainer}
inactiveSlideShift={0}
onSnapToItem={(index) => setIndex(index)}
scrollInterpolator={scrollInterpolator}
slideInterpolatedStyle={animatedStyles}
useScrollView={true}
/>
<Text style={styles.counter}>
Test
</Text>
</View>
);
}
const styles = StyleSheet.create({
carouselContainer: {
marginTop: 50
},
itemContainer: {
width: ITEM_WIDTH,
height: ITEM_HEIGHT,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'dodgerblue'
},
itemLabel: {
color: 'white',
fontSize: 24
},
counter: {
marginTop: 400,
fontSize: 30,
fontWeight: 'bold',
textAlign: 'center',
backgroundColor: "black",
}
});
export default VideoCarousel;

Cannot read property 'navigation' of undefined Evaluating App.js Loading App.js

Looking to have button enter go into another screen:
need help with navigation screen.
I keep getting error:
Cannot read property 'navigation' of undefined
Evaluating App.js
Loading App.js
TypeError: Cannot read property 'navigation' of undefined
https://snack.expo.io/#ganiyat1/colorful-thrills
import * as React from 'react';
import { Text, View, StyleSheet, ImageBackground, Image, Button } from 'react-native';
import Constants from 'expo-constants';
import { StackNavigator} from 'react-navigation';
import Books from './components/Books';
// You can import from local files
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
const Book = StackNavigator({
Books: { screen: Books },
});
const { navigate } = this.props.navigation;
export default function App() {
return (
<View style={styles.container}>
<View style={styles.topContainer}>
<Text style={styles.title}> Colorful Thrills
</Text >
</View>
<View style={styles.bottomContainer}></View>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={require('./assets/bookcover.png')}
/>
<Text style={styles.paragraph}>
{"\n"} BOOKWORMS, UNITE! {"\n"} {"\n"}
Suspense, Mystery and Thrillers by Authors of Color
</Text>
<Button
color='#ff914d'
title= 'ENTER'
onPress={() =>
navigate('Books')}
/>
</View>
</View>
);
}
In the above code snippet, I don't see a default Navigator being returned form the entry file, which is App.js by default in React Native.
I assume that you just started to learn React Native, so I will spare you all the minor details and walk you through the solution.
I refactored the App.js file to a into a new component file in /components/Home.js.
Added a default stack Navigator in App.js which has two screens, Home and Books.
Now you can access all the Navigation props in your Home and Books component, as it is being declared in the Navigator variable in App.js
Here is a live demo of your code on Expo.
//App.js
import * as React from 'react';
import { Text, View, StyleSheet, ImageBackground, Image, Button } from 'react-native';
import Constants from 'expo-constants';
import { StackNavigator} from 'react-navigation';
import Books from './components/Books';
import Home from './components/Home'
import { Card } from 'react-native-paper';
const Navigator = StackNavigator({
Books: { screen: Books },
Home:{screen:Home}
});
export default function App(props) {
return (
<Navigator />
);
}
//component/Books.js
import React, { useState } from 'react';
import { StyleSheet, SafeAreaView,Button } from 'react-native';
import MaterialTabs from 'react-native-material-tabs';
const Books = (props) => {
const {navigation} = props
const [selectedTab, setSelectedTab] = useState(0);
return (
<SafeAreaView style={styles.container}>
<MaterialTabs
items={['New Releases', 'All', 'BOM']}
selectedIndex={selectedTab}
onChange={setSelectedTab}
barColor="#1fbcd2"
indicatorColor="#ff914d"
activeTextColor="white"
/>
<Button
color='#ff914d'
title= 'Home'
onPress={() =>
navigation.navigate('Home')}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default Books
//component/Home.js
import React from 'react'
import {View,Text,StyleSheet,Button,Image} from 'react-native'
const Home = (props) => {
const {navigation} = props
return (
<View style={styles.container}>
<View style={styles.topContainer}>
<Text style={styles.title}> Colorful Thrills
</Text >
</View>
<View style={styles.bottomContainer}></View>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={require('../assets/bookcover.png')}
/>
<Text style={styles.paragraph}>
{"\n"} BOOKWORMS, UNITE! {"\n"} {"\n"}
Suspense, Mystery and Thrillers by Authors of Color
</Text>
<Button
color='#ff914d'
title= 'ENTER'
onPress={() =>
navigation.navigate('Books')}
/>
</View>
</View>
)
}
export default Home
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
},
topContainer: {
flex: 1,
backgroundColor: '#ff914d',
},
bottomContainer: {
flex: 1,
backgroundColor: '#96d0e3',
},
imageContainer: {
position: 'absolute',
width: '100%',
height: '100%',
justifyContent: 'center',
alignItems: 'center',
},
image: {
width: 300,
},
title:{
margin: 24,
marginTop: 50,
fontSize: 40,
fontWeight: 'bold',
textAlign: 'center',
fontFamily: 'GillSans-Italic',
},
paragraph: {
margin: 24,
marginTop: 0,
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
}
});

react native rendering useless gap(area) issue with flex

I am a newcomer for React Native with expo, so still struggling with the flex even though reading many documents. As an attached image, there is a gap, red rectangle area in the image, between header and router style in the Home component. I tried to remove that area but have no idea so far. Could you give me any advice?
Component: Home
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View, Button, FlatList, Dimensions } from 'react-native';
import LocationBar from "./locationBar";
import { Router, Scene } from 'react-native-router-flux';
import Item from "../Item/item";
import Main from "./main";
export default function Home() {
return (
<>
<View style={styles.header}>
<LocationBar />
</View>
<Router style={styles.router}>
<Scene key="root">
<Scene key="main" component={Main} initial={true} />
<Scene key="item" component={Item} />
</Scene>
</Router>
</>
);
}
const width_proportion = '100%';
const height_proportion = '15%';
const styles = StyleSheet.create({
header: {
flex:0.15,
backgroundColor: 'yellow',
width: width_proportion,
},
router: {
flex: 1,
backgroundColor: 'blue',
width: width_proportion,
justifyContent: 'center',
alignItems: 'center'
},
});
Component: Item
import * as React from 'react';
import { View, StyleSheet, Dimensions, Text, Button, FlatList, } from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
const FirstRoute = () => (
<View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const initialLayout = { width: Dimensions.get('window').width };
export default function Item({ menu, itemId }) {
const [index, setIndex] = React.useState(0);
const [routes] = React.useState([
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]);
const renderScene = SceneMap({
first: FirstRoute,
second: SecondRoute,
});
return (
<>
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
>
);
}
const styles = StyleSheet.create({
scene: {
flex: 1,
},
});
Component: Location
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import * as Location from "expo-location";
export default function LocationBar() {
const [lat, setLat] = useState();
const [lon, setLon] = useState();
useEffect(() => {
...
});
return (<View style={styles.container}>
<MaterialIcons name="location-on" size={30} />
<Text>
({lat}-{lon})
</Text>
</View>);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
marginTop: 10
},
});
I got the answer from this post! hideNavBar={true} is the key to hide that area

While adding navigation PLugin its not Working showing error

New to react-native and trying to make react-native with the sample app.
I created Two Screen. LOGIN AND FORM Screen.
I want Once I clicked to login button it will go to form screen. I add library of navigation for routing.
But it shows error.
App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Login from './src/pages/pages/Login';
import Form from './src/pages/pages/Form';
const AppNavigator = StackNavigator({
Login: { screen: Login},
Form: { screen: Form},
});
export default class App extends Component<{}> {
render() {
return (
<View style ={styles.container}>
<AppNavigator/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
Login.js
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Button,
TouchableOpacity
} from 'react-native';
export default class Login extends Component {
state = {
username: '', password: ''
}
onChangeText = (key, val) => {
this.setState({ [key]: val })
}
signUp = async () => {
const { username, password } = this.state
try {
// here place your signup logic
console.log('user successfully signed up!: ', success)
} catch (err) {
console.log('error signing up: ', err)
}
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder='Username'
autoCapitalize="none"
placeholderTextColor='white'
onChangeText={val => this.onChangeText('username', val)}
/>
<TextInput
style={styles.input}
placeholder='Password'
secureTextEntry={true}
autoCapitalize="none"
placeholderTextColor='white'
onChangeText={val => this.onChangeText('password', val)}
/>
<TouchableOpacity
style={styles.button}
onPress={() => this.props.navigation.navigate('Form') } title = "Form"
>
<Text > LOGIN </Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
input: {
width: 350,
height: 55,
backgroundColor: '#ff4000',
margin: 10,
padding: 8,
color: 'white',
borderRadius: 4,
fontSize: 18,
fontWeight: '500',
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
button: {
alignItems: 'center',
backgroundColor: '#58d63b',
padding: 10,
width:320,
height:55
}
})
Form.js
import React, {Component} from 'react';
import {View,Text} from 'react';
export default class Login extends Component {
render() {
return (
<View>
<Text> This Is Form Page</Text>
</View>
);
}
}
index.js
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
THIS IS THE ERROR I HAVE GETTING ALL THE TIME
I tried everything clear cache and re-install npm but no luck.
Anyone can help.It would be great.

Unable to connect mapStateToProps and mapDispatchToProps

I'm getting an error that undefined is not a function(evaluating 'this.props.addTodo(text)')
my code was working fine before i introduces the react-navigation as after that i want to add a todo from my second screen i.e. Counter and want to see whether the list on screen one gets updated or not. but i got stuck at adding a todo on first screen as it is throwing the above error.
I'm a complete begginner in React-native and Redux and also in Js. Btw thanks and in advance
and here is my code:
App.js
import React from 'react';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import TodoApp from './src/TodoApp'
import store from './app/store/index'
import { Provider } from 'react-redux'
import {CounterR} from './app/counterR';
import {Counter} from './app/counter';
import {createStackNavigator, createAppContainer} from 'react-
navigation'
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppContainer />
</Provider>
);
}
}
const stack = createStackNavigator({
Home: CounterR,
Second: Counter
},{
initialRouteName: 'Home'
})
const AppContainer = createAppContainer(stack)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
CounterR.js
import React, { Component } from 'react';
import {View,
TouchableOpacity,
Text,
Dimensions,
StyleSheet,
TextInput,
FlatList,
Keyboard} from 'react-native';
import {connect} from 'react-redux'
import { addTodo } from './actions/index'
import { toggleTodo } from './actions/index'
import {NavigationAction} from 'react-navigation'
import store from './store/index'
import { Provider } from 'react-redux'
const { width, height } = Dimensions.get("window");
export class CounterR extends Component{
state = {
text: ""
}
add = text => {
Keyboard.dismiss()
this.props.addTodo(text)
this.setState({text: ""})
}
render(){
return(
<View style={styles.container}>
<TextInput
style={{borderWidth:.5, width: 300, height: 40}}
defaultValue={this.state.text}
onChangeText={(value) => this.setState({text:value})}/>
<TouchableOpacity
onPress={() => this.add(this.state.text)}>
<Text
style={{fontSize: 18}}>ADD TODO</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Second')}>
<Text
style={{fontSize: 18}}>Second Screen</Text>
</TouchableOpacity>
<FlatList
data= {this.props.todos}
numColumns={1}
keyExtractor= {item => item.id}
renderItem ={({ item }) =>
<TouchableOpacity
onPress={() => this.props.toggleTodo(item)}
style={styles.todoText}>
<Text style={{textDecorationLine: item.completed ? 'line-through' : 'none', fontSize: 20}}>{item.text}</Text>
</TouchableOpacity>
}
/>
</View>
)
}
}
const mapStateToProps = state => ({
todos: state.todos
})
const mapDispatchToProps = dispatch => ({
addTodo: text => dispatch(addTodo(text)),
toggleTodo: item => dispatch(toggleTodo(item))
})
export default connect(mapStateToProps, mapDispatchToProps)(CounterR)
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
todoText: {
width: width,
margin: 10
}
});
Counter.js
import React, { Component } from 'react';
import {View,
TouchableOpacity,
Text,
Dimensions,
StyleSheet,
TextInput,
FlatList,
Keyboard} from 'react-native';
import {connect} from 'react-redux'
import { addTodo } from './actions/index'
import { toggleTodo } from './actions/index'
import { Provider } from 'react-redux'
import store from './store/index'
const { width, height } = Dimensions.get("window");
export class Counter extends Component{
state = {
text: "",
}
addTodo = text => {
Keyboard.dismiss()
this.props.addTodo(text)
this.setState({text: ""})
}
render(){
return(
<View style={styles.container}>
<TextInput
style={{borderWidth:.5, width: 300, height: 40}}
defaultValue={this.state.text}
onChangeText={(value) => this.setState({text: value})}/>
<TouchableOpacity
onPress={() => this.addTodo(this.state.text)}>
<Text
style={{fontSize: 18}}>ADD TODO</Text>
</TouchableOpacity>
</View>
)
}
}
const mapStateToProps = state => ({
todos: state.todos
})
const mapDispatchToProps = dispatch => ({
addTodo: text => dispatch(addTodo(text)),
toggleTodo: item => dispatch(toggleTodo(item))
})
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
todoText: {
width: width,
margin: 10
}
});
app/actions/index.js
import {Keyboard} from 'react-native'
import { ADD_TODO, TOGGLE_TODO } from './actionTypes'
let x = 0
export const addTodo = (text) => ({
type: ADD_TODO,
id: x++,
text: text
})
export const toggleTodo = (item) => ({
type: TOGGLE_TODO,
id: item.id
})
app/actions/actionTypes.js
export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
app/reducers/index.js
import { combineReducers } from 'redux'
import todos from './todos'
export default combineReducers({
todos
})
app/reducers/todos.js
const todos = (state =[], action) => {
switch(action.type){
case 'ADD_TODO':
return [
...state, {
id: action.id,
text: action.text,
completed: false
}
]
case 'TOGGLE_TODO':
return state.map(todo =>
(todo.id === action.id)
?
{...todo, completed: !todo.completed}
:
todo)
default:
return state
}
}
export default todos
app/store/index.js
import { createStore } from 'redux'
import rootReducer from '../reducers'
export default store = createStore(rootReducer)