Ways to write components

  • React
  • Examples
  • Ways to write components

React example • 1 min read

  • Components

The way we write React components has changed with time. We started writing React without JSX, then moved to class components, and now we are in the functional components era.

Below you have a sample of code showing 3 different ways of writing the same component in React:

import React from "react";

// Component without JSX
function Button1(props) {
  return React.createElement("button", {
    children: props.children
  });
}

// Class Component
class Button2 extends React.Component {
  render() {
    return <button>{this.props.children}</button>;
  }
}

// Functional Component
function Button3(props) {
  return <button>{props.children}</button>;
}

function App() {
  return (
    <main>
      <Button1>Button without JSX</Button1>
      <br />
      <Button2>Button as a Class Component</Button2>
      <br />
      <Button3>Button as a Functional Component</Button3>
    </main>
  );
}

export default App;

Example: https://codesandbox.io/s/b9wpdb