React
Contents
About
React is a popular JavaScript library for building user interfaces, particularly single-page applications (SPAs). Developed by Facebook, React allows developers to create reusable UI components with a declarative approach. There are two main types of React:
- ReactJS (for web development)
- React Native (for mobile app development).
This page focuses on ReactJS (People often say React in place os ReactJS) and provides examples primarily using TypeScript, which React fully supports.
Child Pages
Related/Child Pages:
- General:
- React Constructs - some constructs in the React library.
Installing React
To get started with ReactJS, you need to set up a React project. The easiest way is using the `create-react-app` CLI tool:
$ npx create-react-app my-app --template typescript
Navigate to your project directory:
$ cd my-app
Start the development server:
$ npm start
This will create a React application with TypeScript support, and you can view it in the browser at `http://localhost:3000`.
Creating a Hello World in React
To create a simple React component in TypeScript:
HelloWorld.tsx:
import React from "react";
const HelloWorld: React.FC = () => {
return <h1>Hello, World!</h1>;
};
export default HelloWorld;
Use this component in your app:
import React from "react";
import HelloWorld from "./HelloWorld";
const App: React.FC = () => {
return (
<div>
<HelloWorld />
</div>
);
};
export default App;
Run the application to see "Hello, World!" rendered on the screen.
React Templates
Functional Component with Props
interface GreetingProps {
name: string;
}
const Greeting: React.FC<GreetingProps> = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
export default Greeting;
Usage:
<Greeting name="Alice" />
Stateful Component with Hooks
import React, { useState } from "react";
const Counter: React.FC = () => {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
Event Handling
const Button: React.FC = () => {
const handleClick = (event: React.MouseEvent<HTMLButtonElement>): void => {
console.log("Button clicked!");
};
return <button onClick={handleClick}>Click Me</button>;
};
export default Button;
Conditional Rendering
const UserGreeting: React.FC<{ isLoggedIn: boolean }> = ({ isLoggedIn }) => {
return isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>;
};
export default UserGreeting;