Creating a Component
Tutorial: Creating a Component
In this tutorial, you’ll learn how to create a React component using ES6 and JSX. React components are the building blocks of modern UI development, enabling reusable and modular design. By the end of this lesson, you’ll have built your first React component and integrated it into your project.
What You Will Learn
- Setting up a new component file in your project.
- Creating a React component using ES6 class syntax.
- Importing and rendering the component.
- Fixing common issues like invalid JSX and reserved keywords.
Creating Your First Component
-
Set Up a Component Folder
- Create a
components
folder inside yoursrc
directory. - Add a new file named
Portfolio.js
to house your component.
- Create a
-
Write the Component
OpenPortfolio.js
and start defining your component:import React from 'react'; class Portfolio extends React.Component { render() { return ( <div className="portfolio"> <h1>My Portfolio</h1> <p>This is a placeholder for portfolio content.</p> </div> ); } } export default Portfolio;
Key Points:
- Use the
class
keyword to create a component. - Extend
React.Component
to inherit React functionality. - The
render()
method must return JSX.
- Use the
Importing and Rendering the Component
-
Import the Component
Open your main client file (e.g.,index.js
orApp.js
) and import the new component:import React from 'react'; import ReactDOM from 'react-dom'; import Portfolio from './components/Portfolio'; ReactDOM.render( <Portfolio />, document.getElementById('root') );
-
Run Your Application
Start your development server:npm start
Open the application in your browser to see your
Portfolio
component rendered on the page.
Common Issues and Fixes
1. Invalid JSX
JSX syntax requires all elements to be properly closed.
- Self-closing tags like
<img />
or<hr />
must include a/
.
2. Reserved Keywords
The keyword class
is reserved in JavaScript. Use className
instead for JSX:
<div className="portfolio"></div>
3. Exporting Components
Ensure your component is exported using export default
. Without this, your component cannot be imported elsewhere.
Refactoring HTML to JSX
If you’re moving HTML into JSX, ensure:
- All tags are closed properly.
- Reserved keywords like
class
are replaced withclassName
. - Inline styles are converted to JavaScript objects:
<div style={{ color: 'blue', fontSize: '14px' }}>Text</div>
Summary
Congratulations! You’ve created your first React component using ES6 and JSX. This foundational step sets the stage for building more complex and reusable components.
In the next lecture, we’ll explore additional React features to enhance your components and workflows.