Back to blog

JavaScript and React: Creating Your First Component 🖥️

JavaScript is the most popular programming language for front-end web development, and React is a JavaScript library that has become one of the most popular for creating interactive user interfaces. In this tutorial, we're going to create our first React component.

Advertisement

To begin, you need to have Node.js and npm (Node Package Manager) installed on your computer. If you don't already have them, you can download Node.js and npm here. npm will be installed automatically when you install Node.js.

Once installed, you can create a new React project using create-react-app, which is a ready-to-use development environment that comes with everything you need to build a React app:

npx create-react-app my-first-component

Once the project has been created, enter the project directory and start the development server:

cd my-first-componentnpm start

Now, if you open http://localhost:3000 in your browser, you'll see the home page of your new React project.

Creating the Component

Let's create a new component called MyComponent. Inside the src folder, create a new file called MyComponent.jsx. Nele, vamos definir e exportar o nosso componente:

import React from 'react';function MyComponent() {  return <div>Hello World!</div>;}export default MyComponent;

This is our first React component! It is a function that returns what we want to render in the browser - in our case, a div with the text "Hello, world!".

Using the Component

To use our new component, let's import it into our App component, which is the main component of our application. In the App.jsx file, do the following:

import React from 'react';import MyComponent from './MyComponent';function App() {   return(     <div className="App">       <MyComponent />     </div>   );}export defaultApp;

Now, if you open http://localhost:3000 in your browser again, you will see the message "Hello, world!" which is rendered by our MyComponent component.

Conclusion

That's it! You've created and used your first React component. Of course, this is a very basic example, and React components can do much more than that. They can have state, receive props, render other components and much more. But I hope this tutorial has given you an idea of how to start creating your own components using React.

To continue improving your JavaScript and React skills, check out the article on Componentization in React: Organization and Code Reuse.

Advertisement

Let's go! 🦅

Previous post Next post

Comments (0)

This article has no comments yet 😢. Be the first! 🚀🦅

Add comments