0% found this document useful (0 votes)
3 views

Reactcheatsheetjs

Uploaded by

davidrenteria100
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Reactcheatsheetjs

Uploaded by

davidrenteria100
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

REACT.

JS

React.js
TABLE OF CONTENTS

Preface 1
Introduction 1
React.js Overview 1
A "Hello Word" Component 1
Component Specification 2
Using State And Properties 2
Using Context 4
Using AJAX 5
Component Styling 5
DOM References 6
Validating Properties 6
Custom Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
The Flux Application Architecture 7
Testing Components 8
React Addons 9

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


1 REACT.JS

PREFACE
PREFACE creates a virtual representation of the DOM in
memory and updates only the parts that have
Welcome to the dynamic world of React.js, a changed in batches. This minimizes the number
cutting-edge JavaScript library that has of direct manipulations to the actual DOM,
revolutionized the landscape of front-end resulting in faster rendering.
development. In this cheatsheet, we embark on a
• Unidirectional Data Flow: React follows a
journey into the heart of React.js, exploring its core
unidirectional data flow, which means that
principles, capabilities, and the transformative
data flows in a single direction through the
impact it has had on building interactive and
components. This makes it easier to understand
efficient user interfaces.
and debug the application, as data changes are
predictable.
INTRODUCTION
INTRODUCTION
• JSX (JavaScript XML): React uses JSX, a syntax
This cheatsheet is designed to be a quick reference, extension for JavaScript that looks similar to
providing concise and essential information about XML or HTML. JSX allows you to write HTML-
the fundamental aspects of React.js, a JavaScript like code in your JavaScript files, making it
library for building user interfaces. Whether you’re more readable and expressive.
a beginner getting started with React or an • React Router: For building single-page
experienced developer looking for a quick applications with multiple views, React Router
reference, this cheatsheet is designed to help you is commonly used. It enables navigation among
navigate and understand React’s key concepts and views of different components, managing the
features. URL, and updating the UI accordingly.

• State and Props: React components can have


REACT.JSOVERVIEW
REACT.JS OVERVIEW
state, which represents the data that can
change over time. Components can also receive
React.js is a popular JavaScript library for building
data from a parent component through props
user interfaces, especially for single-page
(properties), making it easy to pass data down
applications where the user interacts with the page
the component hierarchy.
without having to reload it. Developed and
maintained by Facebook, React simplifies the • Lifecycle Methods: React components have
process of building UI components by using a lifecycle methods that allow you to execute
declarative syntax and a component-based code at various points in a component’s life,
architecture. such as when it is created, updated, or
destroyed. This provides hooks for performing
Here are some key concepts and features of React: actions at specific times in the component’s
lifecycle.
• Declarative Syntax: React allows you to
describe how your UI should look at any given When working with React, you’ll need to install
point in time, and it automatically updates and Node.js and you will typically use a React-powered
renders the components when the data tool like Create React App or framework like,
changes. This is in contrast to imperative Next.js, Remix, Gatsby or Expo to set up your
programming, where you would specify exactly project and then build your components to create a
how to achieve a task step by step. dynamic and interactive user interface.
Frameworks provide features that most apps and
• Component-Based Architecture: React
sites eventually need, including routing, data
applications are built using components, which
fetching, and generating HTML. The combination of
are reusable, self-contained pieces of code that
these features makes React a powerful and efficient
manage their state and can be composed to
library for building modern web applications.
build complex UIs. Components make it easier
to maintain and reason about your code.
AA"HELLO
"HELLOWORD"
WORD"COMPONENT
COMPONENT
• Virtual DOM: React uses a virtual DOM to
improve performance. Instead of updating the Below is an example of a component that renders a
actual DOM every time the state changes, React message customizable based on input data.

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


2 REACT.JS

Read/write Fields Description


import React from 'react';
setState Function used to update
the component’s state.
// Functional component
const HelloWorld = (props) => {
return ( Component Api Description

<div> useState Hook that allows


<p>{props.message}</p> functional components
</div> to have local state.
); useEffect Hook for handling side
}; effects in functional
components. It is also
// Example usage used to implement
const App = () => { component lifecycle
return ( related functionality.
<div> useContext Hook that allows
<h1>Greetings</h1> functional components
<HelloWorld message="Hello, to subscribe to context
World!" /> changes.
</div> useReducer Hook for managing
); complex state logic in
}; functional components.
useCallback Memoizes a callback
export default App; function to prevent
unnecessary re-renders.

In this example: useMemo Memoizes the result of a


computation to optimize
• The HelloWorld component is a functional performance.
component that takes a message prop. It returns
useRef Creates a mutable object
JSX, which represents the structure of the UI. It
that persists across
extracts the message prop using destructuring
renders.
and displays it inside an <p> element, wrapped
in a <div>.
These are fundamental aspects of a functional
• The App component renders the HelloWorld component in React. Keep in mind that the
component and passes the prop with the component API and available hooks may evolve as
message "Hello, World!". React is updated, so always refer to the official
React documentation for the latest information.
COMPONENTSPECIFICATION
COMPONENT SPECIFICATION
USINGSTATE
USING STATEAND
ANDPROPERTIES
PROPERTIES
Below is a table outlining the React functional
component specification. Understanding when to use state and props is
crucial for designing React components effectively.
Read/write Fields Description State is more suitable for managing internal
props Object containing the component data that can change, while props are
properties passed to the used for passing data between components in a
component. controlled and unidirectional manner. Below is a
table describing the differences between state and
state Object representing the props in React, along with guidance on when to use
internal state of the each.
component.

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


3 REACT.JS

Aspect State Props user interactions form input.

Definition Internal data External data Use Props When:


managed by a passed to a
component. component. • Passing data from a parent component to a
child component.
Mutability Can be changed Immutable;
using setState cannot be • Configuring child components with data
method. changed by the received from a parent.
component.
• Establishing communication between
Initialization Defined within Received from a components in a React application.
the component parent
using useState. component. Let’s update the "Hello World" example to include
both props (external data) and state (internal data),
Scope Local to the Received from a
as well as functions to alter the state. In the
component parent
following example, we’ll use the useState hook to
where it is component; can
manage the component’s internal state.
defined. be accessed by
child
components. import React, { useState } from
Change Changes are Changes are 'react';
Trigger triggered by triggered by a
events or async parent const HelloWorld = (props) => {
operations component // State for the internal message
within the updating the const [internalMessage,
component. prop.
setInternalMessage] = useState(
Purpose Represents data Provides a way 'Default Internal Message');
that can change for a parent
over time component to // Function to update the internal
within the pass data down message
component. to its children.
const updateInternalMessage = ()
Immutability Follows the Immutable; => {
Principle principle of should not be setInternalMessage('New Internal
immutability; modified by the Message');
should not be receiving
};
modified component.
directly.
return (
Ownership Owned and Owned by the <div>
managed by the parent <p>External Message (from
component component and
props): {props.message}</p>
itself. passed down.
<p>Internal Message (from
state): {internalMessage}</p>
Use State When:
<button onClick=
• Managing and representing internal state {updateInternalMessage}>Update
within a component. Internal Message</button>
</div>
• Needing to trigger re-renders based on events
);
or asynchronous operations within the
component.
};

• Handling data that is expected to change


const App = () => {
during the component’s lifecycle e.g., tracking
return (

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


4 REACT.JS

<div>
<h1>Greetings</h1> // Create a context with a default
<HelloWorld message="Hello, theme
World!" /> const ThemeContext = createContext(
</div> 'light');
);
}; const HelloWorld = (props) => {
const [internalMessage,
export default App; setInternalMessage] = useState(
'Default Internal Message');

In this updated example:


const updateInternalMessage = ()
• The HelloWorld component now has an internal
=> {
state called internalMessage managed by the setInternalMessage('New Internal
useState hook. Message');
};
• The updateInternalMessage function modifies
the internal state using the setInternalMessage
function, and it is triggered by a button click.
// Use context to get the current
theme
• The external message is still passed as a prop to
const theme = useContext
the HelloWorld component.
(ThemeContext);
USINGCONTEXT
USING CONTEXT
return (
<div style={{ background: theme
Context in React is a feature that allows you to
share data such as themes, user authentication
=== 'dark' ? '#333' : '#fff', color:
status, language preferences or any other global theme === 'dark' ? '#fff' : '#333'
state across components in a tree without explicitly }}>
passing props at every level. Context is often used <p>External Message (from
to avoid "prop drilling," where you pass props props): {props.message}</p>
down multiple levels of nested components. <p>Internal Message (from
state): {internalMessage}</p>
How to Use Context:
<p>Theme (from context):
{theme}</p>
• Create a Context: Use createContext() to
create a context object.
<button onClick=
{updateInternalMessage}>Update
• Provide a Context Value: Use a Provider
Internal Message</button>
component to specify the value you want to
</div>
share.
);
• Consume the Context: Use the useContext hook };
or the Consumer component to access the context
value in consuming components.
const App = () => {
// Use ThemeContext.Provider to
Let’s modify the above example to include a context
that provides a theme, in addition to using props set the theme for the entire app
and state. return (
<ThemeContext.Provider value=
"dark">
import React, { useState, <div>
createContext, useContext } from <h1>Greetings</h1>
'react'; <HelloWorld message="Hello,

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


5 REACT.JS

World!" /> } catch (error) {


</div> setError(error);
</ThemeContext.Provider> }
); };
};
fetchData();
export default App; }, []); // Empty dependency array
means the effect runs once after the
initial render
In this example:

• We’ve created a ThemeContext using


return (
createContext('light'), providing a default <div>
theme of 'light'. {data && (
<div>
• The ThemeContext.Provider in the App
<h1>Data Loaded:</h1>
component sets the theme to 'dark' for the
entire app.
<pre>{JSON.stringify(data,
null, 2)}</pre>
• The useContext(ThemeContext) hook in the
</div>
HelloWorld component allows us to access the
)}
current theme from the context.
{error && <p>Error: {error
• The component’s styling is adjusted based on .message}</p>}
the theme. </div>
);
USINGAJAX
USING AJAX };

In React, you can make AJAX (Asynchronous


export default MyComponent;
JavaScript and XML) requests using various
techniques. One common approach is to use the
fetch function or third-party libraries like Axios, In this example:
jQuery or Zepto. Let’s see an example.
• The fetchData function is an asynchronous
function that makes the API request using the
import React, { useState, useEffect fetch function.
} from 'react';
• The useEffect hook is used to trigger the data
fetching when the component mounts.
const MyComponent = () => {
const [data, setData] = useState • The fetched data is stored in the component’s
state using the setData function.
(null);
const [error, setError] = • Error handling is done using the try/catch
useState(null); block, and errors are stored in the component’s
state using the setError function.
useEffect(() => {
const fetchData = async () => { COMPONENTSTYLING
COMPONENT STYLING
try {
In React, you can apply styles to components using
const response = await
a variety of methods. The two most popular ones
fetch('https://api.example.com/data'
are using inline styles or using CSS modules. Lets
);
see an example of using both methods at the same
const result = await time.
response.json();
setData(result);

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


6 REACT.JS

// styles.module.css useEffect(() => {


.container { // Access the DOM element using
color: red; current property of the ref
font-size: 12px; myInputRef.current.focus();
// ... other CSS properties }, []); // Empty dependency array
} means the effect runs once after the
initial render
import React from 'react';
import styles from return <input ref={myInputRef} />;
'./styles.module.css'; };

const MyComponent = () => {


In the example above, we set focus on the input
const mystyle = {
field right after its initial render.
color: 'blue',
border: '1px solid black', VALIDATINGPROPERTIES
PROPERTIES
// ... other CSS properties VALIDATING
}; In React, you can validate the props that a
component receives using PropTypes. PropTypes is a
return ( built-in type-checking feature that helps you catch
<div style={mystyle}> common bugs by ensuring that components receive
<p className={styles. the correct types of props. React will issue warnings
container}>Hello, Styling!</p> to the console if the passed props do not match the
</div> specified types. Below is an example of how you
); can use PropTypes for prop validation.

};
import PropTypes from 'prop-types';
export default MyComponent;
const MyComponent = ({ name, age,
DOMREFERENCES
REFERENCES isStudent }) => {
DOM
// Component logic
In React, accessing DOM elements directly is };
generally avoided, and the preferred approach is to
use React’s virtual DOM and state to manage MyComponent.propTypes = {
component rendering. However, there are name: PropTypes.string.isRequired,
situations where you may need to interact with the // String is required
actual DOM, such as focusing an input field, age: PropTypes.number,
measuring an element, or integrating with third- // Number is optional
party libraries that require direct DOM access.
isStudent: PropTypes.bool
.isRequired, // Boolean is required
React provides a feature called refs that can be used
to get a reference to a DOM element. Refs are
};
created using the useRef hook method.
MyComponent.defaultProps = {
age: 25,
import React, { useRef, useEffect } };
from 'react';

Here are some common PropTypes:


const MyComponent = () => {
const myInputRef = useRef(null);

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


7 REACT.JS

• PropTypes.string: A string. if the prop is valid, and a Error


object if the prop is invalid.
• PropTypes.number: A number.
const isValidEmail = (props,
• PropTypes.bool: A boolean. propName, componentName) => {
• PropTypes.array: An array. const value = props[propName];
• PropTypes.object: An object.
if (!value || typeof value !==
• PropTypes.func: A function.
'string' || !value.includes('@')) {
• PropTypes.node: A React node (e.g., string or return new Error(`Invalid email
ReactElement). prop in ${componentName}.`);
• PropTypes.element: A React element. }

• PropTypes.instanceOf(MyClass): An instance of a
return null;
particular class.
};
• PropTypes.oneOf(['value1', 'value2']): A value
from a specified set.

• PropTypes.oneOfType([PropTypes.string, const MyComponent = ({ name, email


PropTypes.number]): One of a specified type. }) => {
• PropTypes.arrayOf(PropTypes.number): An array // Component logic
of a certain type.
};
• PropTypes.objectOf(PropTypes.string): An
object with values of a certain type.
// Combine your custom validation
• PropTypes.shape({ name: PropTypes.string, with standard PropTypes checks of
age: PropTypes.number }): An object with your component.
specific properties.
MyComponent.propTypes = {
Using .isRequired ensures that the prop is passed
name: PropTypes.string.isRequired,
and is of the specified type. // Standard PropTypes check
email: isValidEmail,
PropTypes are a powerful tool for catching potential // Custom validation check
issues early in development and providing clear };
documentation for your components. They are
particularly helpful when working on larger
projects or collaborating with a team. THEFLUX
THE FLUXAPPLICATION
APPLICATION
ARCHITECTURE
ARCHITECTURE
CUSTOM VALIDATION
Flux is an application architecture developed by
Custom prop validation in React allows you to Facebook for building client-side web applications.
define your own rules for prop validation beyond It complements the React library but can be used
the standard data types provided by PropTypes. You with other libraries or frameworks as well. Flux is
can create custom validation functions and use not a library or a framework but rather a set of
them to check the values of your props. design principles that guide how data flows through
an application. The primary goal of Flux is to
provide a unidirectional data flow, making it easier
import PropTypes from 'prop-types'; to reason about and manage the state of a complex
application.
// Define a function that checks
whether the prop meets your custom The key components of the Flux architecture
validation criteria. include:
// The function should return null

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


8 REACT.JS

• Actions: Actions represent events or user user interacts with the updated views, creating
interactions that trigger changes in the new actions and continuing the unidirectional
application state. They are simple objects flow.
containing a type property that describes the
action, and optionally, a payload with This architecture helps to maintain a clear and
additional data. predictable flow of data in the application, making
it easier to understand and debug. It’s important to
• Dispatcher: The Dispatcher is responsible for
note that Flux is a set of design principles, and there
distributing actions to registered stores. It is a
are various implementations and variations of Flux
central hub that manages the flow of data
in the wild, including popular libraries like Redux.
within the application. When an action is
dispatched, the Dispatcher notifies all
TESTINGCOMPONENTS
TESTING COMPONENTS
registered stores about the action. In other
words it is essentially an event system and
Testing React components can be done using testing
there can be only one global dispatcher.
libraries such as Jest and React Testing Library.
• Stores: Stores contain the application state and Let’s create a simple example of testing the "Hello
logic for handling actions. They respond to World" component using these libraries.
actions by updating their state and emitting
change events. Each store is responsible for a Firstly, you’ll need to install the necessary packages
specific domain or part of the application state. by running the following command:
A Store is a singleton and its the only entity in
the application that is aware of how to update npm install --save-dev jest @testing-
library/react @testing-library/jest-dom
data.

• Views (React Components): Views are React Now, let’s create a test file for our "Hello World"
components that display the application’s user component.
interface. They subscribe to changes in the
stores and update their presentation
accordingly. Views can trigger actions based on import React from 'react';
user interactions. import { render, screen, fireEvent }
from '@testing-library/react';
• Action Creators: Action Creators are utility
import '@testing-library/jest-
functions that encapsulate the logic for creating
actions. They are responsible for defining the dom/extend-expect'; // for
different types of actions that can occur in the additional matchers
application.
import HelloWorld from '
The data flow in Flux follows a unidirectional cycle: ./HelloWorld'; // Assuming your
component is in HelloWorld.js
• Action Creation: A user interacts with the
application, triggering the creation of an action
describe('HelloWorld Component', ()
by an Action Creator.
=> {
• Dispatch: The Action is dispatched to the test('renders the component with
Dispatcher, which forwards it to all registered
the provided props', () => {
stores.
const { container } = render(
• Store Update: Stores receive the action and <HelloWorld message="Testing Hello
update their state based on the action type. World" />);
They emit a change event to notify the views.

• View Update: Views (React components) // Check if the component


receive the change event and update their renders correctly
presentation based on the new state from the expect(container.firstChild
stores. ).toMatchSnapshot();
• User Interaction: The cycle repeats when the

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


9 REACT.JS

// Check if the rendered text


matches the provided message "scripts": {
expect(screen.getByText('Testing "test": "jest"
Hello World')).toBeInTheDocument(); }
});
Then, run the tests by issuing the npm test
test('updates internal message on command.
button click', () => {
render(<HelloWorld message= REACTADDONS
REACT ADDONS
"Initial Message" />);
The table below provides an introduction to some
// Check if the initial message popular React addons. These addons enhance and
is rendered extend the capabilities of React applications,
expect(screen.getByText('Initial covering areas such as routing, state management,
styling, animations, testing, and more. Keep in mind
Message')).toBeInTheDocument();
that the React ecosystem evolves, and new addons
may emerge, so it’s always a good idea to check the
// Trigger the button click to
official documentation for the latest information.
update the internal message
fireEvent.click(screen. Addon Description
getByText('Update Internal Message
React Router A complete routing
'));
solution for React
applications. Allows for
// Check if the internal message
navigation between
is updated after the button click views in a React app.
expect(screen.getByText('New
Redux A state management
Internal Message'
library for managing the
)).toBeInTheDocument();
state of a React
});
application in a
}); predictable way.

React-Redux Official bindings for


This test file includes two tests: using Redux with React.
Provides the connect
• renders the component with the provided function to connect
props: components to the
◦ Checks if the component renders correctly Redux store.
with the provided prop. Redux Thunk Middleware for Redux
◦ Verifies if the rendered text matches the that allows you to write
provided message. asynchronous logic in
your Redux actions.
• updates internal message on button click:
Styled-components A CSS-in-JS library for
◦ Checks if the initial message is rendered.
styling React
◦ Simulates a button click to update the components. Allows you
internal message. to write actual CSS in
your JavaScript files.
◦ Verifies if the internal message is updated
after the button click.

To run the tests, add the following script to your


package.json:

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


10 REACT.JS

Addon Description

React Helmet A library for managing


the document head in
React applications.
Useful for updating
meta tags and titles
dynamically.

React-Query A library for managing,


caching, and updating
remote data in React
applications.

Formik A form management


library for React. Makes
it easy to handle form
state, validation, and
submission.

Yup A JavaScript schema


builder for value
parsing and validation.
Often used with Formik
for form validation.

React Spring A spring-physics-based


animation library for
React. Enables smooth
and natural animations
in React components.

Enzyme A JavaScript testing


utility for React that
makes it easy to test
React components'
output and behavior.

React DevTools A browser extension


that allows you to
inspect and debug React
component hierarchies
in your application.

JCG delivers over 1 million pages each month to more than 700K software
developers, architects and decision makers. JCG offers something for everyone,
including news, tutorials, cheat sheets, research guides, feature articles, source code
and more.
CHEATSHEET FEEDBACK
WELCOME
support@javacodegeeks.com

Copyright © 2014 Exelixis Media P.C. All rights reserved. No part of this publication may be SPONSORSHIP
reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, OPPORTUNITIES
mechanical, photocopying, or otherwise, without prior written permission of the publisher. sales@javacodegeeks.com

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!

You might also like