React.js, often referred to as React, is a popular JavaScript library for
building user interfaces. Whether you’re a seasoned developer or just starting
out, having a cheat sheet at your fingertips can be incredibly handy.
In this article, we’ll provide you with a powerful React.js cheat sheet packed
with simple definitions and practical examples to help you build dynamic and
interactive web applications.
Let’s dive into the cheat sheet with simplified definitions and illustrative
examples –
1. Introduction to React.js
React.js is a JavaScript library for building user interfaces. It helps
developers create reusable UI components that update efficiently and keep the
user interface in sync with the data.
2. Basic Concepts
Components
Components are the building blocks of a React application. They are
self-contained, reusable pieces of UI that can be composed together to create
a complete user interface.
// Example of a functional component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
JSX (JavaScript XML)
JSX is a syntax extension for JavaScript that allows you to write HTML-like
code within your JavaScript code. It makes it easier to define the structure
of React components.
const element = <h1>Hello, world!</h1>;
Props
Props (short for properties) are inputs to a React component. They allow you
to pass data from a parent component to a child component.
function Greeting(props) {
return <p>Hello, {props.name}!</p>;
}
State
State is a way to store and manage data that can change over time within a
component. It’s managed using the ‘useState’ hook or within class components.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
// ...
}
Lifecycle Methods
Lifecycle methods allow you to perform actions at different stages of a
component’s lifecycle. However, with the introduction of hooks, they are less
commonly used.
3. Creating Components
Functional Components
Functional components are JavaScript functions that return JSX elements. They
are easier to read, test, and maintain.
const Welcome = (props) => {
return <h1>Hello, {props.name}</h1>;
};
Class Components
Class components are ES6 classes that extend ‘React.Component’. They have a
render method and can utilize lifecycle methods.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
4. Working with Props
Props allow you to pass data from parent to child components. They are
read-only and help you customize component behavior.
// ParentComponent.js
function ParentComponent() {
return <ChildComponent name="Alice" />;
}
// ChildComponent.js
function ChildComponent(props) {
return <p>Hello, {props.name}!</p>;
}
5. Managing State
State is used to manage data that can change within a component. It’s
typically initialized in the component’s constructor or using hooks.
// Using Class Component
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return <p>Count: {this.state.count}</p>;
}
}
// Using Functional Component with useState hook
function Counter() {
const [count, setCount] = useState(0);
// ...
}
6. Lifecycle Methods
Lifecycle methods allow you to perform actions at different stages of a
component’s existence, such as mounting, updating, and unmounting.
class MyComponent extends React.Component {
componentDidMount() {
console.log('Component did mount');
}
componentDidUpdate() {
console.log('Component did update');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <p>Component Lifecycle</p>;
}
}
7. Handling Events
React allows you to attach event handlers to components using camelCase naming
conventions.
function ButtonExample() {
const handleClick = () => {
console.log('Button clicked');
};
return <button onClick={handleClick}>Click me</button>;
}
8. Conditional Rendering
Conditional rendering allows you to show different components or content based
on conditions.
function Greeting(props) {
if (props.isLoggedIn) {
return <p>Welcome back, user!</p>;
} else {
return <p>Please log in.</p>;
}
}
9. Lists and Keys
When rendering lists, React requires a unique ‘key’ prop for each item to help
with efficient updates.
function ListExample(props) {
const items = props.items.map((item) => (
<li key={item.id}>{item.name}</li>
));
return <ul>{items}</ul>;
}
10. Styling in React
You can apply styles to React components using inline styles or CSS classes.
function StyledComponent() {
const style = {
color: 'blue',
fontSize: '16px'
};
return <p style={style}>Styled text</p>;
}
11. Fetching Data
You can use the ‘fetch’ API or third-party libraries like ‘axios’ to fetch
data from APIs.
function DataFetching() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => setData(data));
}, []);
return <p>{data}</p>;
}
12. Forms and Controlled Components
Controlled components keep the form data in the component’s state, making it
easy to manage and validate.
function FormExample() {
const [inputValue, setInputValue] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
console.log('Submitted:', inputValue);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
13. React-Router
React Router is a popular library for handling navigation in React
applications.
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Linkto="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</div>
</Router>
);
}
14. Context API
The Context API allows you to manage a global state that can be accessed by
nested components without prop drilling.
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
15. Hooks
Hooks are functions that allow you to use state and lifecycle features in
functional components.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((prevSeconds) => prevSeconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Seconds: {seconds}</p>;
}
16. Redux (State Management)
Redux is a state management library that helps manage complex application
states.
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};
const store = createStore(reducer);
function Counter() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT'
})}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT'
})}>Decrement</button>
</div>
);
}
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
17. Testing React Applications
Testing is an essential part of software development. React applications can
be tested using libraries like ‘react-testing-library’ and ‘enzyme’.
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders the app', () => {
render(<App />);
const linkElement = screen.getByText(/Welcome/i);
expect(linkElement).toBeInTheDocument();
});
18. Best Practices
- Keep components small and focused on a single responsibility.
- Use functional components whenever possible.
- Prefer hooks over class-based components for state and side effects.
- Use prop types or TypeScript for type checking.
- Organize your codebase using folder structures and module imports.
Conclusion
This React.js cheat sheet covers essential concepts and practical examples to
help you build powerful and interactive web applications. Whether you’re a
beginner or an experienced developer, having these definitions and examples at
your fingertips can greatly enhance your productivity and understanding of
React.js. Happy coding!