ReactNative HTMLButtonElement gives error at emulator - html

I have the following code:
import React from 'react';
import {StyleSheet, View} from 'react-native';
interface MyButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
dataCode: string;
}
class MyButton extends React.Component<
MyButtonProps & React.HTMLProps<HTMLButtonElement>,
{}
> {
render() {
return <button {...this.props} />;
}
}
const App = () => {
const _onPressButton = (event: any) => {
let params: string = (event.currentTarget as MyButton).props.dataCode;
fetch(`http://10.18.1.19/switch?${params}`);
};
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<MyButton
dataCode="binary=111111111111111111111111&protocol=1&pulselength=3"
onClick={_onPressButton}
title="Test"
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
buttonContainer: {
margin: 20,
},
});
export default App;
and I have error message when I use button ws. Button.
ReactNativeJS: Invariant Violation: View config getter callback for
component button must be a function (received undefined). Make
sure to start component names with a capital letter.
How can I extend a HTML button element?

Related

Call function to update Context in React Native

I am having problems calling a function in React Native. I simply want to change the value of 'Context'. Here is some code, first the script for 'context':
//LogContext.js
import React, { useState } from 'react'
export const LogContext = React.createContext({
set: "en",
login: "false"
})
export const LogContextProvider = (props) => {
const setLog = (login) => {
setState({set: "jp", login: login})
}
const initState = {
set: "en",
login: "false"
}
const [state, setState] = useState(initState)
return (
<LogContext.Provider value={state}>
{props.children}
</LogContext.Provider>
)
}
and the 'app.js' code:
//app.js
import React, { useState, useContext } from 'react';
import { Button, Text, TextInput, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { LogContextProvider, LogContext } from './LogContext'
function HomeScreen({ navigation }) {
const state = useContext(LogContext);
return (
<>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Passed config: {JSON.stringify({state})}</Text>
<Text>Home Screen</Text>
</View>
{state.login === 'false' ? (
<Button
title="Go to Login"
onPress={() => navigation.navigate('Login')}
/>
) : (
<Button title="Stuff" onPress={() => navigation.navigate('DoStuff')} />
)}
</>
);
}
function LoginScreen({ navigation }) {
const state = useContext(LogContext);
//do stuff to login here...
state.setLog('true'); //not functional...
return (
<LogContext.Provider value={'true'}> //value={'true'} also not functional...
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Login Screen</Text>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
</View>
</LogContext.Provider>
);
}
function StuffScreen({ navigation }) {
//do other stuff here...
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="DoStuff" component={StuffScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Obviously I am not too familiar with React Native. Any advice on how to call the "setLog()" function as to enable an update of the value for the 'Context' global variable would be greatly appreciated. I thank you in advance.
I am trying to modify my "App()" function to wrap the Navigator within the provider as suggested by another user...however this following is completely non-functional...suggestions appreciated:
const Stack = createStackNavigator();
function App() {
const [data, setData] = useState({
set: 'en',
login: 'false',
});
const state = { data, setData };
return (
<LogContext.Provider value={state}>
<NavigationContainer>
{state.data.login === 'true' ? (
<Stack.Navigator>
<Stack.Screen name="BroadCast" component={VideoScreen} />
<Stack.Screen name="Logout" component={LogoutScreen} />
</Stack.Navigator>
) : (
<Stack.Navigator>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
)}
</NavigationContainer>
</LogContext.Provider>
);
}
The issue you are having is not having a set function in your context and i dont see a need for a separate LogContext provider function.
You can simply do that part in your app.js or whatever the root function. The below example does that. You can see how a state value is passed along with a function to set the values and this can be modified from teh Login component which is inside the provider. If you use a separate provider its a bit confusing. The below is a working example without the navigation part to give you an idea.
const LogContext = createContext({
data: {
set: 'en',
login: 'false',
},
});
export default function App() {
const [data, setData] = useState({
set: 'en',
login: 'false',
});
const state = { data, setData };
return (
<LogContext.Provider value={state}>
<View style={{ flex: 1 }}>
<Text>{JSON.stringify(state.data)}</Text>
<Login />
</View>
</LogContext.Provider>
);
}
const Login = () => {
const state = React.useContext(LogContext);
return (
<View>
<Button
onPress={() => state.setData({ set: 'bb', login: 'true' })}
title="Update"
/>
</View>
);
};
To modify your code, you should wrap the main navigator inside the LogContext.Provider and maintain the state there which will help you do the rest.
Feel free to ask any further clarification :)

JSON Parse Error : Unexpected Identifier "Undefined"(React Native)

I'm trying to use Async storage to store two Text Input values stored as an object and pass it to a different view where they'll be displayed on a button press.
As mentioned in other StackOverflow posts I've used JSON.parse and JSON.stringify to pass the object as JSON data, still for some reason I;m getting the error JSON Parse Error: Unexpected Identifier "Undefined"(React Native)
Add Data
class AddData extends React.Component {
constructor(props) {
super(props);
this.state = {
text1: '' ,
text2: ''
};
}
render() {
function BtnPress() {
alert('Hi')
}
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
<TextInput
style={{height: 40,width:200}}
onChangeText={(text1) => this.setState({input1: text1})}
/>
<TextInput
style={{height: 40,width:200}}
onChangeText={(text2) => this.setState({input2: text2})}
/>
<Button
onPress={() => {
AsyncStorage.setItem('user', JSON.stringify({
name:'Rohit',
email: 'rohitgird12gmail.com'
}));
this.props.navigation.navigate('Home', {});
}}
title="Submit"
/>
</View>
);
}
}
View to Display Data
class DetailsScreen extends React.Component {
displayName = async ()=> {
try {
const myArray = await AsyncStorage.getItem('user');
if (myArray !== null) {
alert(JSON.parse(myArray.name));
}
} catch (error) {
alert(error)
}
}
render() {
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
<Button
onPress={this.displayName}
title="Get Data"
/>
</View>
);
}
}
It looks like const myArray = await AsyncStorage.getItem('user'); is returning undefined while you defended yourself from null only, which is not sufficient here.
Antoher possible problem lies here : JSON.parse(myArray.name). Are you sure it's not supposed to be JSON.parse(myArray).name?

How to call image from JSON that has local path in React Native

import React, { Component } from 'react';
import {
ScrollView,
StyleSheet,
} from 'react-native';
import axios from 'axios';
import CarDetail from '../components/CarDetail';
class CarList extends Component {
state = { cars: [] };
componentDidMount() {
axios.get('https://www.website.com/ajx/home_ajx/lister')
.then(response => this.setState({ cars: response.data.data[0]['S1']
}));
//Add an if statement here to notify the user when the request fails
}
renderCars() {
return this.state.cars.map(model =>
<CarDetail key={model.title} modelprop={model} />
);
}
render() {
console.log(this.state);
return (
<ScrollView>
{this.renderCars()}
</ScrollView>
);
}
}
export default CarList;
And the image path in the JSON file is as below:
"image": "data/models/peugeot-2008-138twf_600X400_.jpg",
Below is where I'm calling the image in another component
const CarDetail = ({ modelprop }) => {
const { image } = modelprop;
return (
<Card>
<CardSection>
<View>
<Image style={imageStyle}
source={{ uri: props.modelprop.image }}
/>
</View>
I believe I need to use some kind of prefix maybe in my Global.js which I couldn't find or figure out.
Any help is highly appreciated.
Mostly like your code has a bug:
const CarDetail = ({ modelprop }) => {
const { image } = modelprop;
return (
<View>
<Image
style={imageStyle}
source={{ uri: image }}
/>
</View>
);
}
If the image is something like data/models/peugeot-2008-138twf_600X400_.jpg, you should use `${Global.imageUrlPrefix}${image}` to concat all.

calling function from PhotoGrid render function Library

i am using a PhotoGrid Library in react native to populate the list of photo on my apps. how to call a function from the render function ? it show this error when i call a function called "deva" on my OnPress method in <Button onPress={()=>{this.deva()}}><Text>Bondan</Text></Button> . here is my code...
import React from 'react';
import { StyleSheet, Text, View, WebView, TouchableOpacity, Image, Alert, Dimensions} from 'react-native';
import {DrawerNavigator} from 'react-navigation'
import {Container, Header, Button, Icon, Title, Left, Body, Right, Content} from 'native-base'
import PhotoGrid from 'react-native-photo-grid'
import HomeScreen from './HomeScreen'
export default class Recomended extends React.Component {
constructor() {
super();
this.state = { items: [],
nama : ""
}
}
goToBufetMenu(){
this.props.navigation.navigate("BufetMenu");
}
componentDidMount() {
// Build an array of 60 photos
let items = Array.apply(null, Array(60)).map((v, i) => {
return { id: i, src: 'http://placehold.it/200x200?text='+(i+1) }
});
this.setState({ items });
//this.setState({ nama: "Bondan"});
//this.props.navigation.navigate("BufetMenu");
}
deva() {
Alert.alert('deva');
}
render() {
return (
<Container style={styles.listContainer}>
<PhotoGrid
data = { this.state.items }
itemsPerRow = { 3 }
itemMargin = { 3 }
renderHeader = { this.renderHeader }
renderItem = { this.renderItem }
style={{flex:2}}
/>
</Container>
);
}
renderHeader() {
return(
<Button onPress={()=>{this.deva()}}><Text>Bondan</Text></Button>
);
}
renderItem(item, itemSize) {
return(
<TouchableOpacity
key = { item.id }
style = {{ width: itemSize, height: itemSize }}
onPress = { () => {
this.deva();
}}>
<Image
resizeMode = "cover"
style = {{ flex: 1 }}
source = {{ uri: item.src }}
/>
<Text>{item.src}</Text>
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
height: 587,
},
gridText: {
color: '#fff',
textAlign: 'center',
fontStyle: 'normal',
fontSize : 12
},
listContainer: {
height: Dimensions.get('window').height - (Dimensions.get('window').height*53/100),
}
});
You are loosing context of this. You need to either use arrow functions or bind the functions.
Example
constructor() {
super();
this.state = { items: [],
nama : ""
};
this.renderHeader = this.renderHeader.bind(this);
this.renderItem = this.renderItem.bind(this);
}
OR
renderHeader = () => {
// rest of your code
}
renderItem = (item, itemSize) => {
// rest of your code
}
Either change your deva method definition to an arrow function -
deva= () => {
Alert.alert('deva');
}
Or bind the deva method to this inside your constructor
constructor() {
super();
this.state = { items: [],
nama : ""
}
this.deva = this.deva.bind(this)
}
You get the error because when the deva method is invoked using this.deva(), the javascript runtime cannot find the property/function deva on the this it's called with (which is the anonymous callback passed to onPress in this case). But if you bind this to deva beforehand, the correct this is being searched by the javascript runtime.

React-Native: Type Error when parsing JSON

I was trying to implement a News App. It should show a list of news headlines on start with thumbnail image and description and then on clickinh the url should be opened in browser. But, i am stuck on halfway getting a Type Error.
Here are the codes of my NewsList and NewsDetail files.
NewsList.js
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import axios from 'axios';
import NewsDetail from './NewsDetail';
class NewsList extends Component {
constructor(props) {
super(props);
this.state = {
news: []
};
}
//state = {news: []};
componentWillMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=in&apiKey=MYAPIKEY')
.then(response => this.setState({news: response.data }));
}
renderNews() {
return this.state.news.map(newsData =>
<NewsDetail key={newsData.title} newsData={newsData} />
);
}
render() {
console.log("something",this.state);
return (
<ScrollView>
{this.renderNews()}
</ScrollView>
);
}
}
export default NewsList;
NewsDetail.js
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import Card from './Card';
import CardSection from './CardSection';
import Button from './Button';
import NewsList from './NewsList';
const NewsDetail =({ newsData }) => {
const { title, description, thumbnail_image, urlToImage, url } = newsData;
const { thumbnailStyle,
headerContentStyle,
thumbnailContainerStyle,
headerTextStyle,
imageStyle } =styles;
return(
<Card>
<CardSection>
<View>
<Image
style={thumbnailStyle}
source={{uri: urlToImage}}
/>
</View>
<View style={headerContentStyle}>
<Text style={headerTextStyle}>{title}</Text>
<Text>{description}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={imageStyle}
source={{uri:urlToImage}}
/>
</CardSection>
<CardSection>
<Button onPress={() =>Linking.openURL(url)} >
ReadMore
</Button>
</CardSection>
</Card>
);
};
export default NewsDetail;
StackTrace of the Error i am getting
TypeError: this.state.news.map is not a function
This error is located at:
in NewsList (at App.js:11)
in RCTView (at View.js:78)
in View (at App.js:9)
in App (at renderApplication.js:35)
in RCTView (at View.js:78)
in View (at AppContainer.js:102)
in RCTView (at View.js:78)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:34) NewsList.renderNews
NewsList.js:21:31 NewsList.proxiedMethod
createPrototypeProxy.js:44:29 NewsList.render
NewsList.js:31:18 NewsList.proxiedMethod
createPrototypeProxy.js:44:29 finishClassComponent
ReactNativeRenderer-dev.js:8707:30 updateClassComponent
ReactNativeRenderer-dev.js:8674:11 beginWork
ReactNativeRenderer-dev.js:9375:15 performUnitOfWork
ReactNativeRenderer-dev.js:11771:15 workLoop
ReactNativeRenderer-dev.js:11839:25 Object.invokeGuardedCallback
ReactNativeRenderer-dev.js:39:9
App.js
import React from 'react';
import { AppRegistry, View } from 'react-native';
import Header from './header';
import NewsList from './NewsList';
//create component
const App = () => {
return(
<View style={{ flex:0 }}>
<Header headerText={'Headlines'} />
<NewsList />
</View>);
}
export default App;
AppRegistry.registerComponent('news', () => App);
The error you're getting - TypeError: this.state.news.map is not a function, means that news is not an array.
By checking your api response you should do:
this.setState({news: response.data.articles }).
You can actually go to https://newsapi.org/v2/top-headlines?country=in&apiKey="MY_API_KEY" in the browser or use a tool like curl or Postman to check what the response is. The data response is an object, but you need an array. articles is most likely the property you are after.
You may also want to check that this is an array and update what is displayed appropriately.
.then(response => {
const news = response.data.articles;
if (Array.isArray(news)) {
this.setState({ news });
} else {
this.setState({ errorMessage: 'Could not load any articles' });
}
});