Boidurja Talukdar
Boidurja Talukdar

Reputation: 696

function componentDidMount not firing in react native

The function componentDidMount is not firing.

This is some of my code:

import React, { Component } from 'react';
import { Block } from 'galio-framework';

export function FriendRequests ( ) {

    const username = 'abcd';

    componentDidMount = () => {
        alert("abcd");
    }

    return (
    line number 37:    <Block>....</Block>
    )
}

Upvotes: 0

Views: 425

Answers (2)

Bhagwat K
Bhagwat K

Reputation: 3142

You are using the functional component which doesn't have the lifecycle methods.

Solution 1:

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class FriendRequests extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

 componentDidMount = () => {
        alert("abcd");
    }

  render() {
    return (
      <View>
        <Text> Your text Here </Text>
      </View>
    );
  }
}

export default FriendRequests;

Solution 2:

If you want to use it as functional component then you can use the React Hook and can make use of useEffect() method from the hook instead of componentDidMount. method to handle after render stuff.

Upvotes: 3

Gaurav Roy
Gaurav Roy

Reputation: 12235

First of all,

export function FriendRequests ( ) {


    componentDidMount = () => {
        alert("abcd");
    }

    return (
        ....
    )
}

this is a functional component, and functional component dont have any inbuilt functions like componentDidMount. Only class based components have access, So try this:

UPDATE:

export class FriendRequests extends React.Component {

    componentDidMount() {
        alert("abcd");
    }

    render() {
        return (
            <View>
                <Text>hey</Text>
            </View>
        );
    }
}

hope it helps. feel free for doubts

Upvotes: 1

Related Questions