Home React
Post
Cancel

React

Install

Make sure you have Node.js installed. Then run the following command to make shure the latest version of create-react-app is installed globally.

1
2
npm uninstall -g create-react-app
npm install -g create-react-app

Usage

Create a new app with the name my-app and run it on localhost:3000.

1
2
3
npx create-react-app my-app
cd my-app
npm start

Components

Everything in React is a component. Components are the building blocks of React apps. A component is a JavaScript function that returns HTML elements to be rendered to the page. Components can be written as a function or a class.
By default, React components are written as JavaScript functions and everything is in the App.js file. The App.js file is the root component of the application. It is the first component that is rendered when the application starts.
It is usefull to put all components in .jsx: files and in a folder called components. This makes it easier to find the components and to reuse them in other projects.
It makes sense to write components as const functions and functions as normal functions. This makes it easier to read and understand the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
export const App = () => {
  return (
    <div>
      <Navbar />
      <div className='main'>
        {movies.map(createCard)}
      </div>
      <Footer />
    </div>
  );
};

export default App;
  • use { } to write js expressions in components
  • use className instead of class to set the class of an element (use camelCase instead of kebab-case as in html)
  • use export default to export a component
1
2
3
4
5
6
7
8
9
10
11
12
13
export const Card = (props) => {
  return (
    <a href='#home'>
      <img className='card' src={props.src} alt='#' />
    </a>
  );
};

function createCard(movie) {
  return <Card key={movie.id} src={movie.posterurl} />;
}

export { createCard };

If you want to map a component every time you need to use the key attribute. The key attribute is used to identify each element in the list. It is used by React to keep track of the list items and to update the list efficiently. The key attribute is not accessible in the component. Every element in the list needs to have a unique key attribute.

documentation

This post is licensed under CC BY 4.0 by the author.