I just started trying to learn ReactJS and found some tutorials. All of them tell me to run npx create-react-app .
or such.
The problem I have is when I see their App.js they all have classes, whereas mine has:
function App() {...}
instead of
class App extends Component
Same with the import statements too. Theirs say:
import React, { Component } from 'react'
while mine says
import React from 'react'
I'm not exactly sure what's wrong, and how can I solve this?
There are multiple ways to define a React component – either as class component, or a function component.
Nowadays, the latter, function component, is mostly the preferred way, unless you want to do something really fancy with the component's lifecycle methods.
Class components are still valid, as well, though, and you will frequently find them in older tutorials online.
Create react app creates a functional component App
to get you started:
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
This can be rewritten as a class component like so:
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
As you can see, it's slightly more verbose, but it's perfectly valid.
You can just replace the function with the class you found in the example code of the tutorial you're following.
Don't forget to import Component
in addition to react
, in this case – for class components, this is necessary because the class needs to extend Component
.