3 Ways to Create React Components

<!-- React Version 16 --><script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script><script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.js"></script>

Method #1: Using a Variable Function (depreciated)

Note: At the time of writing this article React version 15 was the latest version. This method of creating a react component has depreciated starting from Version 16 and will only work for React versions 15 or earlier.
If you still want to see it working, change the script tags pointing to the React CDN to:

<!-- React Version 15 --><script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js"></script><script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.1/react-dom.js"></script>
var MyComponent = React.createClass({
render() {
return <div>
<h1>Hello World!</h1>
<p>This is my first React Component.</p>
</div>
}
})
<div id=”react-component”></div>
ReactDOM.render(<MyComponent />, document.getElementById('react-component'))

Method #2: Using a Class

For those who are not caught up with Javascript evolution news, the language now supports classes. You can create a javascript class the extends (a.k.a. inherits) React’s Component class and re-write the above method:

class MyComponent extends React.Component{
render() {
return <div>
<h1>Hello World!</h1>
<p>This is my first React Component.</p>
</div>
}
}

Method #3: Using a Stateless Functional Component

Sounds scary when you say it out loud. But it’s really means a simple function (as opposed to a variable) that returns a react component. Here you will see some new ES6 syntax that makes javascript codes shorter and easier to read.

const MyComponent = () => {
return <div>
<h1>Hello World!</h1>
<p>This is my first React Component.</p>
</div>
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adham El Banhawy

Adham El Banhawy

Software Developer, blogger, and tech enthusiast. Currently developing software at IBM.