React promotes the idea of thinking in components. It is about being able to break down the UI into a Component hierarchy. Each component will be created in a separate file.
// Greeting.jsx
function Greeting(){
return <h1>Hello World</h2>
}
export default Greeting
Each component needs to be exported and then imported following the syntax of the ES6 module.
// App.jsx
import Greeting from "./Greeting";
function App(){
return <Greeting />;
}
export default App;
Just as you can compose functions or classes to create more complex solutions/models, you can compose simpler components to create more complex ones.
For example, you can create a Title
component, a Content
component, and a Comment
component. Then, you can compose them into an Article
component.
// Article.jsx
import Title from "./Title";
import Content from "./Content";
import Comment from "./Comment";
function Article(){
return (
<Title />
<Content />
<Comment />
);
}
export default Article;
Moreover, you can compose the Article
component with other components to create a more complex component.
// App.jsx
import Header from "./Header";
import Footer from "./Footer";
import Sidebar from "./Sidebar";
import Article from "./Article";
function App(){
return (
<Header />
<Sidebar />
<Article />
<Footer />
);
}
export default App;
This way, you can create a complex UI by composing simpler components. This approach makes the code more readable, maintainable, and testable.
It is a common practice to store components in a components
directory. This directory will contain all the components used in the application. Each component will be stored in a separate file.
src/
components/
Header.jsx
Footer.jsx
Sidebar.jsx
Article.jsx
Title.jsx
Content.jsx
Comment.jsx
Greeting.jsx
...