The various ways to create and manage React components, the plethora of state management tools that have emerged, and so on are the focus of these challenges. What we can do today in React (Community-based Selection) is bring the most common practices to the table and discuss them.

Among them, we’ll learn some useful themes and terminology from React. These topics include:

directory

  • The normal Component
  • Props to verify
  • Interactions between Components
  • Initializes the Component
  • ES6+ Components (different from normal Components)
  • Stateless component

This article is pretty basic, so you might find yourself reading something you already know. If you are looking for more advanced topics, you can read our
Other React articles.

The regular React Component

By general, AND I mean common, you’ve probably seen it in most code libraries and articles:

var Hello = React.createClass({ render: function() { return <div>Hello {this.props.name}</div>; }}); ReactDOM.render( <Hello name="World" />, document.getElementById('container') );Copy the code

Keep in mind that routine does not mean best practice. The React documentation promotes it simply because it’s so common.

The react. createClass function must be passed as an argument of type Object. This object defines a React component. The Render attribute is required and the most important attribute. It is responsible for parsing HTML in JavaScript, JSX.

Web applications are interesting only when they are dynamic. Any UI library provides a way to pass data to the system. The idea behind React is to pass data through props Objects. So when you look at JSX below:

<h1>My name is {name}</h1>
Copy the code

We tell React that when the component is called, the name property with the value should be passed like render in the example above:

<Hello name="World" />
Copy the code

The rendering method requires a component output and DOM output. This is the basic anatomy of a React component.

Related courses: Getting started with React

States & Props

Dynamic applications must pass data to the system. In React, data movement occurs mainly between components that provide raw data and external services (such as HTTP, localStorage).

Props are immutable, which means they can only be passed down from the parent component and cannot be changed. This presents a challenge because modern Web programs cannot have all the data ready when the page loads. Ajax and other events can happen that can cause changes in the data, and when the data comes back, the data needs to be updated. That’s where the React state comes in.

When we initialize React, we define an initial state and keep state in sync with the props. Once state is updated, props can easily stay in sync:

var Counter = React.createClass({ getInitialState: function() { return { counter: 0 }; }, render: function() { return <div> <h2>{this.props.name}</h2> {this.state.counter} </div>; }}); ReactDOM.render( <Counter name={'Counter'} />, document.getElementById('container') );Copy the code

The parent component

It’s pretty straightforward. If a component renders another component in its render, the renderer is the render owner (parent). The renderer owns the rendered component and controls it.

Let’s look at another example:

var CounterDisplay = React.createClass({
    render: function(){
    return <div>{this.props.counterProp}</div>
  }
})

var Counter = React.createClass({
    getInitialState: function() {
    return {
        counter: 0
    };
  },
  render: function() {
    // Child component rendered
    // React will throw an error if the the DOM doesn't have a single parent
    return <div>
            <h2>{this.props.name}</h2>
            <CounterDisplay counterProp={this.state.counter}></CounterDisplay>
      </div>;
  }
});

ReactDOM.render(
  <Counter name={'Counter'} />,
  document.getElementById('container')
);
Copy the code

Counter now renders another component, CounterDisplay. Counter is responsible for managing and synchronizing the props of CounterDisplay. You can see how we pass state to the child components via props. These props could also have been named counters like state, but that might have been confusing for beginners, so I gave it a different name.

Component interaction

What if we had a button (or more) in the child component to increase or decrease the integer (state) managed in the parent component? What do we do?

React component interactions come in two forms: data flows from parent to child components and data flows from child to parent. We have seen how to implement the data flow from parent to child components using props.

To implement data passing between children and parents in React, we use handlers that pass from the parent to the child as props. The parent component knows that such an activity could happen to the child, so it sets up a handler for when it changes. More like an event:

Var CounterDisplay = react. createClass({render: function(){ // Calls the handler props once events are fired return <div> <div>{this.props.counterProp}</div> <button onClick={this.props.incrementCounter}>+</button> <button onClick={this.props.decrementCounter}>-</button> </div> } })Copy the code
Var Counter = react.createclass ({getInitialState: function() {return {Counter: 0}; }, handleIncrement(){ // Update counter state this.setState({counter : this.state.counter+1}); }, handleDecrement(){ // Update counter state this.setState({counter : this.state.counter-1}); }, render: function() { // Pass down handlers to CounterDisplay component return <div> <h2>{this.props.name}</h2> <CounterDisplay counterProp={this.state.counter} incrementCounter={this.handleIncrement} decrementCounter={this.handleDecrement}></CounterDisplay> </div>; }}); ReactDOM.render( <Counter name={'Counter'} />, document.getElementById('container') );Copy the code

When the CounterDisplay component is clicked, their handler function is not anywhere in the component; instead, the handler is handled by the parent component Counter. The handler, in turn, updates the state using the this.setState () method, and the counter display (subcomponent) props is updated

Initializes the Component

It is not only state that has the ability to reset the initial value using the getInitialState method. If desired, you can also set default values for props to be used on component loads. To do this, you can use the getDefaultProps method:

getDefaultProps: function() {
     return {
       name: 'Counter'
     };
},
Copy the code

This is useful for setting default values in your application.

Prop validation

The good news about the React component is that I’ve seen developers love and emphasize its usability. You can put any component in an application that does what it’s designed to do as long as you follow its rules. How can I make my own rules when making my own reusable components? Props validation is the answer to your question.

Validation by name helps you be sure that the data flowing into the component is organized the way you expect it to be. Users can’t pass in strings of data that you set as an array. That’s how it works

var CounterDisplay = React.createClass({ render: function(){ // Calls the handler props once events are fired return <div> <div>{this.props.counterProp}</div> <br /> <button onClick={this.props.incrementCounter}>+</button> <button onClick={this.props.decrementCounter}>-</button> </div>  }, // Setup validation for each props propTypes: { // Must be a number counterProp: React.PropTypes.number.isRequired, // Must be functions incrementCounter: React.PropTypes.func.isRequired, decrementCounter: React.PropTypes.func.isRequired } })Copy the code

If all you need is the validation type, not whether it exists, you can ignore isRequired:

propTypes: {
    // Should be a number
    counterProp: React.PropTypes.number,
    // Should be functions
    incrementCounter: React.PropTypes.func,
    decrementCounter: React.PropTypes.func
   }
Copy the code

Class Component (ES6)

React. CreateClass is not the only possible way to create a valid React component. With ES6 (which is really cool), we can use CLSAA to create the React component.

// Extends React.Compoent
class Comment extends React.Component {
 // Render method now a class member rather than
 // object property
  render(){
    return <h1>{this.props.name}</h1>;
  }
}

 React.render(<Comment name={'Comment'}/>, document.getElementById('container'));
Copy the code

Component name is the name of the class, the class inheritance React.Com ponent function.

Set state in class

If you use ES6 to construct components, the way you set state will also change a bit;

class Comment extends React.Component {
   constructor(props) {
        super(props);
        this.state = {
            counter: 0
        };
  }
  render(){
    return <h1>{this.props.name}</h1>;
  }
}

 React.render(<Comment name={'Comment'}/>, document.getElementById('container'));
Copy the code

The initial state is now set in the class constructor instead of using getInitialState.

Initialize and validate props in class

// Validation
Comment.propTypes = {
        counterProp: React.PropTypes.number.isRequired,
    incrementCounter: React.PropTypes.func.isRequired,
    decrementCounter: React.PropTypes.func.isRequired
};
// Defaults
Comment.defaultProps = {
    name: 'Counter'
};
Copy the code

There are some subtle differences, but these are the ones you should be aware of. You can read about the differences.

Stateless component

When the component is not handling any state, you can use these features:

function CommentDisplay(props) {
  return <div>
            <div>{props.counterProp}</div>
        <br />
        <button onClick={props.incrementCounter}>+</button>
        <button onClick={props.decrementCounter}>-</button>
        </div>
}
Copy the code

It’s that simple!