How to write your first React.js component

React’s function and class components, props, state, and event handlers


Screenshot captured from my Pluralsight course — React.js: Getting Started
Screenshot captured from my Pluralsight course — React.js: Getting Started
Screenshot captured from my Pluralsight course — React.js: Getting Started

Let’s write a React component.

mountNode.innerHTML = 'Hello!!';
3 == '3'
function Button() {
  return (
    <button>Go</button>
  );
}
function Button() {
  return (
    React.createElement("button", null, "Go")
  );
}
ReactDOM.render(<Button />, mountNode);
ReactDOM.render(<Button label="Save" />, mountNode);
function Button(props) {
  return (
    <button>{props.label}</button>
  );
}

Making the component interactive

class Button extends React.Component { 
}
render() {
  return (
    <button>1</button>
  );
}
constructor(props) {
  super(props);
  this.state = { counter: 1 };
}
render() {
  return (
    <button>{this.state.counter}</button>
  );
}
class Button extends React.Component {
  state = { counter: 1 };
  
  render() {
    return (
      <button>{this.state.counter}</button>
    );
  }
}
function F() {}<button onClick={F} />
<button onClick={() => {}} />
class Button extends React.Component {
  state = { counter: 1 };
  
  handleClick = () => {
    console.log('Button is clicked!!');
  };
  
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.counter}
      </button>
    );
  }
}
// WRONG:
this.state.counter = this.state.counter + 1;
this.setState((prevState) => {});
this.setState((prevState) => ({
  counter: prevState.counter + 1 
}));
class Button extends React.Component {
  state = { counter: 1 };
  
  handleClick = () => {
    this.setState((prevState) => ({
      counter: prevState.counter + 1 
    }));
  };
  
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.counter}
      </button>
    );
  }
}ReactDOM.render(<Button />, mountNode);

This article is a write-up of part of my Pluralsight course — React.js: Getting Started. I cover similar content in video format there.


jsComplete EdgeCoders

We write about the new and leading edge technologies with a focus on JavaScript

Samer Buna

Written by

Author for Pluralsight, O'Reilly, Manning, and LinkedIn Learning. Curator of jsComplete.com

jsComplete EdgeCoders

We write about the new and leading edge technologies with a focus on JavaScript