Mlz
Mlz

Reputation: 55

How can I use {...this.props} in a functional component

I bought a React-Native course on Udemy and the guy who teaches React-Native used {...this.props}. But it didn't work for me. Here is the error message.

TypeError: undefined is not an object(evaluating '_this.props')

What should i do?

LoginForm.js

import React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import Input from '../components/Input';
const LoginForm: () => React$Node = () => {
  return (
    <>
      <View>
        <Text style={styles.signInText}>SIGN IN</Text>
        <Input 
          placeholder="Username"
        />
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  signInText:{
    fontWeight:'bold',
    marginVertical:25,
    color:'#189BDD'
  }
});

export default LoginForm; 

Input.js

import React from 'react';
import { StyleSheet, ScrollView, View, TextInput, Image } from 'react-native';
const Input: () => React$Node = () => {
  return (
    <>
      <View>
        <TextInput
          {...this.props}
        />
      </View>
    </>
  );
};

const styles = StyleSheet.create({});

export default Input;

Udemy Teacher SS

Upvotes: 3

Views: 904

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 187034

There are two ways to create a React component: a class or a function.

Input here is a functional component, not a class component.

That means that the props are passed as an argument to your function, rather than as properties of the class instance. this is not used in functional components, only class components.

So decalre your functional component like this:

const Input = (props) => {

And then spread props like this:

{...props}

Upvotes: 2

Brian Thompson
Brian Thompson

Reputation: 14365

this won't exist on a functional component. In a functional component, you access props as a parameter, which you haven't passed.

const Input = (props) => {

...

  <TextInput
    {...props}
  />
}

Upvotes: 4

Related Questions