12
Organizing a React component these days (H1/2018)
source link: https://www.phpied.com/organizing-react-component-h1-2018/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
I started typing an answer to a question by @alexharrisonsax since my React book is written for the recent past (React 14) and things change. Twitter is not great for code discussions, so here goes.
Import dependencies
import React, {Component, Node} from 'react';
Declare the component
class App extends Component {}
Unless it's functional stateless component (preferably), in which case:
const App = ({name, description}) => <div> <h1>{name}</h1> <h2>{description}</h2> </div>;
If using Flow, a good idea is to define the types of properties and state, like:
type Props = { name: string, description: string, }; type State = { theTruth: boolean, };
Then the class declaration becomes:
class App extends Component<Props, State> { state: State = { // property initializer for initial state theTruth: false, }; // optional, only if the initial state is not good enough // or there are other things you need to do constructor(props: Props): void { super(props); this.state = { theTruth: props.description === 'shall set you freeee', }; } render(): Node { return <div>{/* fun with this.props and this.state */}</div>; } }
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK