5

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

1
  • 1
    don't know the answer of how react understand its a react component?, but its called as Stateless Functional Component and used when you want to create a component that doesn't have any state or lifecycle methods means purely used to return a UI. check the stackoverflow DOC on Stateless Functional Component: stackoverflow.com/documentation/reactjs/6588/… Commented Apr 30, 2017 at 7:43

2 Answers 2

3

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>
}
Sign up to request clarification or add additional context in comments.

2 Comments

he is asking How react understand this is a react component ? you are telling the benefits and properties of stateless functional component.
The react developers or someone who make deep analize react code may answer carefully. I think that react see if such function return react component so that finction is react component too.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.