Welcome to this comprehensive guide on Core Components in React JS! In this tutorial, we will dive deep into the world of React JS, focusing on fundamental components like View, Text, and more. By the end of this lesson, you'll have a strong foundation to build your own dynamic web applications! 📝
React components are the building blocks of a React application. A component is a JavaScript function or class that returns a render method, which describes how a part of the UI should look. In simpler terms, components allow you to build reusable and modular pieces of code that can be combined to create complex UIs. 💡
In React, the root component of an application is called App. The App component acts as the main container for all other components. You can think of it as a container for your entire application's UI. 💡
import React from 'react';
function App() {
return (
<div>
This is my App component
</div>
);
}
export default App;To display text in a React component, we can use the <p> tag or any other HTML tags. However, in React, we prefer using <h1> to <h6> tags for heading and <p> for paragraphs. 💡
import React from 'react';
function Header() {
return (
<div>
<h1>Welcome to my React App!</h1>
<p>This is a paragraph inside the Header component.</p>
</div>
);
}
export default Header;React allows you to style components using CSS-in-JS libraries like styled-components or emotion. In this tutorial, we will use styled-components. 💡
import React from 'react';
import styled from 'styled-components';
const HeaderContainer = styled.div`
text-align: center;
padding: 20px;
background-color: lightblue;
`;
function Header() {
return (
<HeaderContainer>
<h1>Welcome to my React App!</h1>
<p>This is a styled paragraph inside the Header component.</p>
</HeaderContainer>
);
}
export default Header;What is the root component of a React application?
Props (short for properties) are a way to pass data from parent components to child components. Props allow you to make components reusable and dynamic. 💡
import React from 'react';
function Greeting(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
}
function App() {
return (
<div>
<Greeting name="John" />
<Greeting name="Jane" />
</div>
);
}
export default App;Unlike props, state is a way to manage and track the internal data of a component. You can think of state as a dynamic property of a component. 💡
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={handleClick}>Increment</button>
</div>
);
}
export default Counter;What is the purpose of state in a React component?
That's it for this lesson on Core Components in React JS! In the next tutorial, we will explore more advanced topics like Hooks, Routing, and Forms. Keep practicing, and happy coding! 💡