Trần Kim Dự
Trần Kim Dự

Reputation: 6102

React component without extend React Component class

I see in some source code, the author wrote a component like this:

import React from 'react';

export const Login = () => (
  <div>
    <h4>Hello World</h4>
  </div>
);

export default Login;

The thing I don't know is:

  1. How react understand this is a react component by only using import
  2. How can I add another callback method, such as viewDidMount ... I have added in code block but it compiles fail.

thanks

Upvotes: 5

Views: 3281

Answers (2)

Merlin -they-them-
Merlin -they-them-

Reputation: 2940

React "knows" that the code you wrote is a React Component because of transpilation. Transpilation is a process that occurs during build time where your code is changed from the code you wrote into something else.

In the case of React and JSX, your code turns into

export const Login = () => (
  React.createElement('div', {},
    React.createElement('h4', {}, 'Hello World')
  );
);

The angle brackets (<) are syntactic sugar for React.createElement and people use the angle brackets because they are simpler to use and type.

Upvotes: 2

user394010
user394010

Reputation: 374

This is functional stateless component. It is for simple components.

You also can add component property types like this:

export const Login = () => (
  <div>
    <h4>Hello World</h4>
  </div>
);

Login.propTypes = {
  username: React.PropTypes.string.isRequired,
}

You can add callback like this:

// this place to define callback is more effective 
const onClick = e => (...)

const Login = props => {
  // or define here if you need access to props in onClick
  const onClick = e => (...)

  return <button onClick={onClick}>Submit</button>
}

Upvotes: 3

Related Questions