Rashomon
Rashomon

Reputation: 6762

Define component as constant

Im following a React Native course and at some point the teacher defines a component as constnat using the following code:

const Comment = (props) =>
  <Text>{props.text}</Text>

However I dont manage to make it work. I made a snack to just try the component individually and it doesnt work: https://snack.expo.io/S1eKSeV-7

I always get the error Invariant Violation: element type is invalid.

What Im doing wrong?

Upvotes: 1

Views: 6486

Answers (3)

bennygenel
bennygenel

Reputation: 24660

You are not exporting your component. That is why you get the error because Comment component is undefined.

import React from 'react'
import {Text} from 'react-native'

const Comment = (props) =>
  <Text>{props.comment.text}</Text>

export default Comment

Upvotes: 4

devserkan
devserkan

Reputation: 17608

This is a functional component. There are two type of components in React: Functional and class components. If you don't need any state or don't use any lifecycle methods in your component you can and should use functional components.

Functional components

const SomeComponent = () => <div>Something</div>;

No need to use an explicit return here since arrow function do this for us if there is one single statement.

With regular function:

function SomeComponent() { return <div>Something</div> };

Class components

class SomeComponent extends React.Component {
    state = { foo: "bar" };
    someLifeCycleMethod() {
       ....
    }
    render() {
        return( <div>Something</div>);
    }
}

When you don't understand something always refer to official documentation.

The problem you are having is not directly related to component type. As suggested in another answer your component probably is not exported.

Upvotes: 4

Yossi
Yossi

Reputation: 6027

This will work:

const Comment = (props) => {
  return (
    <Text>{props.text}</Text>
  );
};

Upvotes: -1

Related Questions