I am working on React-Native, i want to call a function from different class but when i am trying to do it's showing some error.
Class A
import B from './B.js';
class A extends Component {
_onItemPressed(item){
B.abc();
}
render() {
return (
<TouchableHighlight
underlayColor={Colors.colors.lightgrey}
style={{padding: 15}}
onPress={this._onItemPressed.bind(this)}>
<Text>Click Me !</Text>
</TouchableHighlight>
);
}
}
Class B
class B extends Component {
abc(){
alert('Hello World');
}
render() {
return (
<View>
<Text>Welcome to React Native</Text>
</View>
);
}
}
But error message is coming after pressing the button in Class A, 'undefined is not a function (evaluating 'B.default._abc()')'
Please kindly go through my post and suggest me some solution.
Thanks
You have two options, either to use an object or use class name, let's start with object
class B {
abc() {
alert("Hello World");
}
}
const b = new B();
export default b;
So when you call this file you can access the function abc like the following
import b from './B.js';
class A extends Component {
_onItemPressed(item){
b.abc();
}
...
The other way is to use class instead as follow
class B{}
B.abc = function(){
alert("Hello World");
}
module.exports = {
functions: B
};
So when you call this file you can access the function abc like the following
import b from './B.js';
class A extends Component {
_onItemPressed(item){
b.functions.abc();
}
...
Note: B class should not be a component, you can use it as a helper class.
also, you can enhance the way you deal with the object using singleton pattern as I already mention in
React native- Best way to create singleton pattern
UPDATE: If you insist to use component instead of a class function, you can call it through reference, as follows:
export default class B extends Component {
constructor(props) {
super(props);
this.abc = this.abc.bind(this);
}
abc(){
alert('Hello World');
}
render() {
return null
}
}
now in A component you can call B by reference
import B from "./B.js";
class A extends Component {
_onItemPressed(item) {
this._b.abc();
}
render() {
return (
<TouchableHighlight
underlayColor={Colors.colors.lightgrey}
style={{ padding: 15 }}
onPress={this._onItemPressed.bind(this)}
>
<Text>Click Me !</Text>
<B ref={ref => (this._b = ref)} />
</TouchableHighlight>
);
}
}
You dont initiate your class, to solve this you need to change the B.abc() to new B().abc();
I noticed you didn't export your class B. Try
class B extends Component {
static abc(){
alert('Hello World');
}}
export default B
then import it in class A
import B from './B';
Let me know if this worked for you.
You have to create the parent with a constructor, access to super method for extend well the Component Class, then export the parent class and extend it on the Class A where you have access to this functions by this context of the class
export default class B extends Component {
constructor(props){
super(props);
}
abc(){
alert('Hello World');
}
render() {
return (
<View>
<Text>Welcome to React Native</Text>
</View>
);
}
}
import B from './B.js';
export default class A extends B {
_onItemPressed(item){
this.abc();
}
render() {
return (
<TouchableHighlight
underlayColor={Colors.colors.lightgrey}
style={{padding: 15}}
onPress={this._onItemPressed.bind(this)}>
<Text>Click Me !</Text>
</TouchableHighlight>
);
}
}
I tried various solutions on this page but that didn't work. I am copying a solution from another web page here. Very simple and impressive. Might help someone looking for a simple solution:
How to Call Another Class Function From Default Class in React Native
Here is the complete example code:
import { StyleSheet, View, Alert, Platform, Button } from 'react-native';
export default class MyProject extends Component {
constructor(props) {
super(props)
Obj = new Second();
}
CallFunction_1=()=>{
Obj.SecondClassFunction() ;
}
CallFunction_2=()=>{
Obj.SecondClassFunctionWithArgument("Hello Text");
}
render() {
return (
<View style={styles.MainContainer}>
<View style={{margin: 10}}>
<Button title="Call Another Class Function Without Argument" onPress={this.CallFunction_1} />
</View>
<View style={{margin: 10}}>
<Button title="Call Another Class Function With Argument" onPress={this.CallFunction_2} />
</View>
</View>
);
}
}
class Second extends Component {
SecondClassFunction=()=>{
Alert.alert("Second Class Function Without Argument Called");
}
SecondClassFunctionWithArgument=(Value)=>{
Alert.alert(Value);
}
}
const styles = StyleSheet.create(
{
MainContainer: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
backgroundColor: '#F5FCFF',
paddingTop: (Platform.OS) === 'ios' ? 20 : 0
}
});
I can see that you are not exporting the class B, you are only importing. Please try adding an export statement at bottom of the class B file like so export default B.
Hope this helps
Make abc function static and export B class.
export default class B extends Component {
static abc(){
alert('Hello World');
}
}
Import the first class in the another class where you want to use the function defined in first class. In this case, We are using a function defined in class1 to class2.
export default class class1 extends React.Component{
constructor(props)
{
...
}
static function(){
...
}
}
**Now import it to another class i:e; class2**
import class1 from 'class1';
export default class class2 extends React.Component{
componentWillMount()
{
class1.function();
}
}
Related
I am just getting started with React native and I came across a rather unexpected bug. Consider the code below
export default class RecipePage extends Component {
state = {
ingredients: ["apple", "orange"]
}
render() {
return (
<View>
<ShowRecipes ingredients={this.state.ingredients} />
</View>
)
}
}
class ShowRecipes extends Component {
render() {
return (
<View>
<Text>This is inside ShowRecipes</Text>
</View>
)
}
}
export default ShowRecipes
I get an error below which points to <ShowRecipes ingredients={this.state.ingredients} />
"TypeError: undefined is not an object"
I am getting this error and I am not able to figure out what's causing it. Can someone please help fix this mistake.
Any help is appreciated.
You should put State in the contructor to get like this this.state.something
Try this code.
export default class RecipePage extends Component {
constructor(props) {
super(props)
this.state = {
ingredients: ["apple", "orange"]
}
}
}
I call a function that is in my Homepage class from my ProfileScreen class that is in the same .js file. I successfully did that, but in that function a setState is called, and when the function is called from the other class, the state doesn't change. How can I get this.state.user in HomePage to change from calling the onPressLogout function in the ProfileScreen class?
export default class HomePage extends Component<Props> {
state = {
email:'',
password:'',
firstname:'',
lastname:'',
user:true,
error: '',
}
onPressLogout(){
firebase = require('firebase');
firebase.auth().signOut()
.then(() => this.setState({
user:false
}))
.catch(() => this.setState({
error: 'Logout Failure',
}))
}
render(){
return <AppContainer>
</AppContainer>;
}
}
class ProfileScreen extends React.Component {
constructor(props) {
super(props);
Obj = new HomePage();
}
render() {
return (
...
<TouchableOpacity style={styles.button} onPress =
{()=>Obj.onPressLogout()}>
</TouchableOpacity>
...
}
}
const TabNavigator = createBottomTabNavigator({
Profile: ProfileScreen,
});
const AppContainer = createAppContainer(TabNavigator);
I get this warning when I run the code and the this.state.user doesn't change:
Warning: Can't call "setState" on a component that is not yet mentioned.
You should pass the function of the parent element into the child element as a prop. Then, you can call it in the child to manipulate the state of the parent class.
Here is an example,
class ChangeButton extends React.Component{
render(){
return (
<Button title="Change" onPress={this.props.updateMainState}/>
)
}
}
export default class App extends React.Component {
state = {
name: 'Fatih'
}
changeName = ()=> {
this.setState({
name: 'Faruk'
})
}
render() {
return (
<View style={styles.container}>
<Text>
{this.state.name}
</Text>
<ChangeButton updateMainState={this.changeName}/>
</View>
);
}
}
In the code above, we passed changeName function into the ChangeButton element. The Button in ChangeButton calls the function of the parent element when you press it, which manipulates the state of the main class.
Here is the working code: ProjectLink
Ive been looking for styling guides for react-admin, using material-ui. But I could not find an example on how it is done for class based components.
I hope someone shares their knowledge.
Thank you in advance.
user2002500. I hope this can help you.
1st, u need to import wtihStyles
import { withStyles } from '#material-ui/core/styles';
2nd, create a variable above class
const styles = {
field: {
widht: '80%' }
}
class Test extends Component {
....
}
3rd, add {...this.props} to a component you want to style
<TextField source= "id" {...this.props}/>
4th, add withStyles when export default
export default withStyles(styles)(Test)
5th, destructuring classes from this.props
render() {
const { classes } = this.props
return(
....
)
}
6th, last finishing back to the component you have add {...this.props},
add className property with classes.image
<TextField source= "id" className={classes.field} {...this.props}/>
Example:
import React, { Component } from 'react';
import { withStyles } from '#material-ui/core/styles';
import { TextField, Edit, SimpleForm } from 'react-admin';
const styles = {
field: {
widht: '80%' }
}
class Test extends Component {
render() {
const { classes } = this.props
return (
<Edit title={'Test'} {...this.props}>
<SimpleForm>
<TextField source= "id" className={classes.field} {...this.props}/>
</SimpleForm>
</Edit>
);
}
}
export default withStyles(styles)(Test)
maybe, this not a good explanation. But i think this the right step if you want use class component then function component.
i want to pass my params value in my custom component so below is my code
Header.js
class Header extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View >
<Text >Title</Text>
<Text>subtitle</Text>
</View>
);
}
}
I call my Header.js from my main.js
class Main extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Header title = {this.props.navigation.state.params.screen_title} subtitle= {this.props.navigation.state.params.subtitle} />
);
}
}
I pass my title and subtitle in my header component , i just wanted to know how can i access my passing variable value in my header component ? your all suggestions are appreciable
Its very simple You can access it by
this.props.title
this.props.subTitle
this.props.nameOfTheProps
I'm implementing the react native swiper (https://github.com/leecade/react-native-swiper) in a project
class MainSwiper extends React.Component {
_onMomentumScrollEnd() {
// Edit some state of the SomeView here...
}
render() {
return (
<Swiper
onMomentumScrollEnd={this._onMomentumScrollEnd}>
<View>
<SomeView />
</View>
// More views here...
</Swiper>
);
}
}
AppRegistry.registerComponent('some_app', () => MainSwiper);
And I want the method _onMomentumScrollEnd() to change some state of the SomeView declared in the JSX.
Suppose SomeView is defined as:
class SomeView extends React.Component {
constructor(props) {
super(props);
this.state = {somestate = 'Hi!'};
}
render() {
return (
<Text>{this.state.somestate}</Text>
);
}
}
I realize I might be approaching this issue in the wrong way, but I don't know how it's done. How can somestate be changed from _onMomentumScrollEnd() (or any other MainSwiper method) and get the SomeView to re-render, i.e. how do I access the SomeViewelement from within a MainSwiper method?
You should pass state to the SomeView component by its props. So you could do
class MainSwiper extends React.Component {
_onMomentumScrollEnd() {
this.setState({somestate: A String})
}
render() {
return (
<Swiper
onMomentumScrollEnd={this._onMomentumScrollEnd}>
<View>
<SomeView somestate={this.state.somestate} />
</View>
// More views here...
</Swiper>
);
}
}
AppRegistry.registerComponent('some_app', () => MainSwiper);
And then in SomeView
class SomeView extends React.Component {
render() {
return (
<Text>{this.props.somestate}</Text>
);
}
}
Notice how the SomeView component became a stateless component by not keeping its own state. It's not mandatory but it's a good practice.