Introduction to React.js for Beginners
Overview of React.js
- What is React.js?: A JavaScript library (not a framework) used to build user interfaces for web applications.
Key Concepts in React.js
- Components: Self-contained sections of code that function as reusable building blocks (like Legos).
- Components can include JavaScript and HTML code.
- JSX (JavaScript XML): A syntax extension that allows you to write HTML-like code within JavaScript files.
- Virtual DOM: A lightweight version of the real DOM. React keeps track of changes in the virtual DOM and updates the real DOM efficiently.
Prerequisites
- JavaScript: Up to arrays, classes, objects, and ES6 features like arrow functions.
- HTML/CSS: Basic knowledge since React components involve rendering HTML and applying CSS.
Installation Instructions
- Node.js: Download from nodejs.org.
- Node.js is a backend JavaScript runtime environment with a package manager (npm).
- Text Editor: Recommend VS Code from code.visualstudio.com.
- Steps for setting up a React project:
- Create a project folder and navigate to it using command prompt or terminal.
- Use the command
npm create vite@latest
to set up a new project with Vite (modern alternative to Create React App).
- Commands to initialize and run the project:
- Change directory:
cd my-react-app
- Install dependencies:
npm install
- Start development server:
npm run dev
Project Folder Structure
- node_modules: Contains external libraries and packages.
- public: Contains public assets like images, fonts, and videos (not bundled in final output).
- src: Main folder for development (99% of work).
- assets: Similar to public, but bundled during final output.
- main.jsx: Functions as the main JavaScript file, where components are imported and rendered.
- app.css & index.css: Stylesheets for the application.
- index.html: Main entry point with a root div and script to the main JavaScript file.
- package.json: Contains metadata about the project, like name, version, and dependencies.
Creating and Using Components
- Creating Components: Example component named
Header.jsx
.
- Components are function-based and return HTML-like code (JSX).
- Use
export default
to export the component.
- Importing Components: Example of importing and using
Header
in App.jsx
.
- JSX requires enclosing tags if returning multiple elements as one component.
Styling Components
- Internal and External CSS: Using different methods to style components.
- Inline styles (less preferred for larger projects).
- CSS modules (to avoid naming conflicts).
- External CSS files (for global styles).
- Example: Styling the header and food components with both inline styles and external CSS.
Props and State
- Props (Properties): Allow passing data from parent to child components.
- State: Managed within a component using hooks like
useState
.
- Prop Types: Ensures correct data types for props.
- Default Props: Provide default values if no props are passed.
- Example of creating and using props in a
Student
component.
Conditional Rendering
- Concept: Render components or elements conditionally based on certain criteria.
- Methods:
- If/Else statements
- Ternary operators
- Logical AND operator for short-circuiting
- Example: Creating a
UserGreeting
component that changes message based on user login status.
Lists and Keys
- Rendering Lists: Use
.map()
to render lists of elements.
- Keys: Unique identifiers for items in a list to help React keep track of changes.
- Example: Rendering a list of fruits with unique keys.
- Sorting and Filtering Lists: Methods to sort arrays or filter out items based on conditions.
Event Handling
- OnClick Event: Handling click events in React.
- Creating Functions:
handleClick
function to handle button clicks.
- Example: Making a button change text on click using an event.
- Other Events: OnChange for form elements like inputs, select, text areas, and radio buttons.
The useState Hook
- Concept: Allows components to manage state.
- Syntax:
const [state, setState] = useState(initialState)
.
- Example: Creating a counter with increment, decrement, and reset buttons.
The useEffect Hook
- Concept: Side effects in functional components.
- Usage: For things like data fetching, subscriptions, or manually changing the DOM.
- Syntax:
useEffect(() => { code }, [dependencies])
.
- Example: Creating a digital clock that updates every second.
Context API
- Concept: Allows sharing values between components without drilling props.
- Creating Context:
createContext()
in a main provider component.
- Using Context:
useContext()
hook to consume the context in child components.
- Example: Sharing a username across several nested components.
useRef Hook
- Concept: Accessing and interacting with DOM elements without causing re-renders.
- Example: Creating a stopwatch component that tracks elapsed time and controls start, stop, and reset.
Putting It All Together
- Example Projects: Building a To-Do list and a Stopwatch.
- Application Structure: How various hooks and concepts come together to build a React application.
Conclusion
React.js is a powerful library for building dynamic and efficient user interfaces. Its component-based architecture, combined with hooks such as useState
, useEffect
, and useContext
, allows developers to create complex applications in a manageable and scalable way.