React Notes 2
React Notes 2
JS
JavaScript library for building user interfaces
What is React?
• From the official React page : A JavaScript library for building user interfaces
• Its not a framework; React does only one thing – create awesome UI!
• React is used to build single page applications.
• React.js is a JavaScript library. It was developed by engineers at Facebook.
• React is a declarative, efficient, and flexible JavaScript library for building
user interfaces.
• It lets you compose complex UIs from small and isolated pieces of code
called “components”.
Client-side Javascript frameworks
• Ember : was initially released in December 2011. It is an older framework that has
less users than more modern alternatives such as React and Vue
• Angular is an open-source web application framework led by the Angular Team at
Google and by a community of individuals and corporations.
• Vue : first released in 2014; is the youngest of the big four, but has enjoyed a recent
uptick in popularity.
• React : released by Facebook in 2013. By this point, FB had already been using
React to solve many of its problems internally.
React itself is not technically a framework; it's a library for rendering UI components.
React is used in combination with other libraries to make applications — React and React
Native enable developers to make mobile applications; React and ReactDOM enable them
to make web applications, etc.
Components
• A Component is one of the core building blocks of React.
• Its just a custom HTML element!
• Every application you will develop in React will be made up of pieces called
components.
Components make the task of building UIs much easier. You can see a UI broken down
into multiple individual pieces called components and work on them independently and
merge them all in a parent component which will be your final UI.
Why react
• Created and maintained by facebook
• Has a huge community on Github
• Component based architecture
• React is fast. Apps made in React can handle complex updates and still feel
quick and responsive.
• React is modular. Instead of writing large, dense files of code, you can write
many smaller, reusable files. React’s modularity can be a beautiful solution to
JavaScript’s maintainability problems.
• React is scalable. Large programs that display a lot of changing data are
where React performs best.
• React is popular.
• UI state becomes difficult to manage with vanilla Javascript
Requirements
• Ensure that NodeJS and typescript are installed
Install TypeScript as follows:
npm install –g typescript
Using create-react app
• npx create-react-app my-app
• cd my-app
• npm start
Understanding the folder structure
Index.html
function App() {
/*return (
<div >
<h2>Welcome to React!</h2>
</div>
);*/
return React.createElement('div',null,'h2','Hi, welcome to React');
}
export default App;
function App() {
/*return (
<div >
<h2>Welcome to React!</h2>
</div>
);*/
return React.createElement('div',null,
React.createElement('h1',{className:'App'},'Hi welcome to React'));
}
export default App;
Understanding JSX
• Eg : const mytag = <h1>Hello React!</h1>;
ReactDOM.render(myelement, document.getElementById('root'));
const myelement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
ReactDOM.render(myelement, document.getElementById('root'));
const myelement = (
<div> If we want to return more
<h1>I am a Header.</h1> elements, we need to wrap
<h1>I am a Header too.</h1> it with one container
</div> element. Notice how we
); are using div as a wrapper
for the two h1 elements.
ReactDOM.render(myelement, document.getElementById('root'));
Creating a functional component
• Components are the essential building blocks of any app created with React
A single app most often consists of many components.
• A component is in essence, a piece of the UI - splitting the user interface into
reusable and independent parts, each of which can be processed separately.
Components are independent and reusable bits of code.
It’s an encapsulated piece of logic.
They serve the same purpose as JavaScript functions, but work in isolation and return
HTML via a render function.
function ExpenseItem(){
return <h2>Expense Item</h2>
}
export default ExpenseItem;
import "./ExpenseItem.css"
return (
<div className="expense-item">
<div>{expDate.toISOString()}</div>
<div className="expense-item__description"> Comments in JSX
<h2>{expTitle}</h2>
<p className="expense-item__price">Rs {expAmount}</p>
</div>
</div>
)
}
export default ExpenseItem;
Outputting dynamic content – another example
//Person.js Wrap dynamic
import React from 'react'; content in JSX in {...}
function App() {
return (
<div className="App">
<h1> Hi, welcome to React</h1>
<Person />
<Person />
<Person />
</div>
);
}
}
PROPS
Passing data via ‘Props’
• “Props” stands for properties.
It is a special keyword in React used for passing data from one component to another.
Props are arguments passed into React components.
props are read-only. So, the data coming from a parent component can't be changed by
the child component.
Props are passed to components via HTML attributes.
Props can be used to pass any kind of data such as: String, Array, Integer, Boolean,
Objects or, Functions
//Person.js
import React from 'react';
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpenseItem expDate={expenses[0].date} expTitle={expenses[0].title}
expAmount={expenses[0].amount}/>
<ExpenseItem expDate={expenses[1].date} expTitle={expenses[1].title}
expAmount={expenses[1].amount}/>
<ExpenseItem expDate={expenses[2].date} expTitle={expenses[2].title}
expAmount={expenses[2].amount}/>
</div>
);
}
export default App;
“Javascript” in components
const ExpenseItem = (props) => {
const month = props.expDate.toLocaleString('en-US', {month: 'long'});
const day = props.expDate.toLocaleString('en-US', {day: '2-digit'});
const year = props.expDate.getFullYear();
return (
<div className="expense-item">
<div>
<div>{month}</div>
<div>{day}</div>
<div>{year}</div>
</div>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
</div>
)
}
export default ExpenseItem;
import ExpenseDate from "./ExpenseDate";
const ExpenseItem = (props) => { Splitting components further
return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
</div>
)
}
export default ExpenseItem;
import "./ExpenseDate.css"
return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;
No parenthesis ()
STATEFUL COMPONENTS
React State
• The state is a built-in React object that is used to contain data or information
about the component.
• A component’s state can change over time; whenever it changes, the
component re-renders.
The change in state can happen as a response to user action or system-generated
events and these changes determine the behavior of the component and how it will
render.
• A component with state is known as stateful component.
return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{title}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;
React Hooks
• Hooks allow us to "hook" into React features such as state and lifecycle methods
React Hooks are special functions provided by React to handle a specific functionality
inside a React functional component.
Eg React provides useState() function to manage state in a functional component.
When a React functional component uses React Hooks, React Hooks attach itself into
the component and provides additional functionality.
return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{title}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;
props and state
• props and state are CORE concepts of React.
Actually, only changes in props and/ or state trigger React to re-render your components
and potentially update the DOM in the browser
• Props : allow you to pass data from a parent (wrapping) component to a child
component.
Eg : AllPosts Component : “title” is the custom property (prop) set up on the
custom Post component.
Post Component: receives the props argument. React will pass one argument to your
component function; an object, which contains all properties you set up on <Post ... /> .
{props.title} then dynamically outputs the title property of the props object - which is
available since we set the title property inside AllPosts component
//AllPosts //Post
const posts = () => { const post = (props) => {
return ( return (
<div> <div>
<Post title="My first Post" /> <h1>{props.title}</h1>
<Post title="My second Post" /> </div>
</div> );
); }
}
props and state
• State : While props allow you to pass data down the component tree (and hence
trigger an UI update), state is used to change the component’s, well, state from
within.
Changes to state also trigger an UI update.
Example: NewPost Component: this component contains state . Only class-based
components can define and use state . You can of course pass the state down to
functional components, but these then can't directly edit it.
class NewPost extends Component { // state can only be accessed in class-based components!
state = {
counter: 1
};
return(
<ChildComponent uname={uname} email={email} />
);
} function App() {
export default ParentComponent; return (
<div className="App">
<h2>Welcome to React!</h2>
const ChildComponent = (props) => { <ParentComponent />
return( ...
<div>
<div>Name : {props.uname}</div>
<div>Email : {props.email}</div>
</div>
);
}
export default ChildComponent;
USING FORM FOR INPUT
const NewExpense = () => {
return(
Adding form inputs <div className="new-expense">
<ExpenseForm />
import "./ExpenseForm.css" </div>
const ExpenseForm = () => { );
return( }
<form> export default NewExpense;
<div className="new-expense__controls">
<div className="new-expense__control">
<label>Title</label>
<input />
</div>
<div className="new-expense__control">
<label>Amount</label>
<input type="number"/>
</div>
<div className="new-expense__control">
<label>Date</label>
<input type="date" min="2019-01-01"
max="2022-12-31" />
</div>
</div>
<div className="new-expense__actions">
<button type="submit">Add Expense</button>
</div>
</form>
);
}
export default ExpenseForm;
Listening to user input
const ExpenseForm = () => {
return (
<div className="App">
<h2>Welcome to React!</h2>
<NewExpense onAddExpense={addExpenseHandler} />
...
); const NewExpense = (props) => {
}
export default App; const saveExpenseDataHandler = (inputExpenseData) => {
const expenseData = {
...inputExpenseData,
id:Math.random().toString()
}
//console.log("In NewExpense ",expenseData)
props.onAddExpense(expenseData)
}
return(...);
}
export default NewExpense;
LIFTING STATE UP
Lifting state up in React.js
• In a typical application, you pass a lot of state down to child components as props.
These props are often passed down multiple component levels.
That's how state is shared vertically in your application.
• Often there will be a need to share state between different components.
The common approach to share state between two components is to move the state to
common parent of the two components.
This approach is called as lifting state up in React.js
React components can manage their own state
Often components need to communicate state to others
Siblings do not pass state to each other directly
State should pass through a parent, then trickle down
App
C1 C2
<div className='expenses-filter__control'>
<label>Filter by year</label>
<select onChange={selectChangeHandler}> ExpenseItem NewExpense ExpensesFilter
<option value='2022'>2022</option>
<option value='2021'>2021</option>
<option value='2020'>2020</option> ExpenseDate ExpenseForm
<option value='2019'>2019</option>
</select>
</div> function App() {
</div> const [filteredYear, setFilteredYear] = useState(2020);
);
}; const selectYearHandler = filteredValue => {
export default ExpensesFilter; setFilteredYear(filteredValue)
}
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpensesFilter onSelectYear={selectYearHandler}/>
WORKING WITH LISTS AND
CONDITIONALS
const SimpleListComponent = () => {
const nums = [1,2,3,4,5] Working with lists
const updatedNums = nums.map((num)=>{
return <li>{num*num}</li>;
});
return(...);
}
export default SimpleListChildComponent;
Working with the expenses list
const expenses = [
{ title: 'Groceries’, amount: 900, date: new Date(2020, 7, 14)},
{ title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ title: 'SofaSet', amount: 25000, date: new Date(2021, 2, 28)}
];
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpenseItem
expDate={expenses[0].date}
expTitle={expenses[0].title}
expAmount={expenses[0].amount}
/>
<ExpenseItem
expDate={expenses[1].date}
expTitle={expenses[1].title}
expAmount={expenses[1].amount}
/>
<ExpenseItem
expDate={expenses[2].date}
expTitle={expenses[2].title}
expAmount={expenses[2].amount}
/>
</div>
);
}
Working with the expenses list
function App() {
const expenses = [
{ title: 'Groceries', amount: 900, date: new Date(2020, 7, 14)},
{ title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ title: 'Sofa Set', amount: 25000, date: new Date(2021, 2, 28)}
];
return (
<div className="App"> {expenses.map(expense =>
<h2>Welcome to React!</h2> (<ExpenseItem
expDate={expense.date}
{expenses.map(expense => { expTitle={expense.title}
return <ExpenseItem expAmount={expense.amount}
expDate={expense.date} />))
expTitle={expense.title} }
expAmount={expense.amount}
/>
})}
{/* <ExpenseItem
expDate={expenses[0].date}
expTitle={expenses[0].title}
expAmount={expenses[0].amount}
/> ... */}
</div>
);
}
export default App;
const DUMMY_EXP = [
Using stateful lists
{ title: 'Groceries', amount: 900, date: new Date(2020, 7, 14)},
{ title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ title: 'New Sofa Set', amount: 25000, date: new Date(2021, 2, 28)}
];
function App() {
const [expenses, setExpenses] = useState(DUMMY_EXP)
const DUMMY_EXP = [
{ id:101, title: 'Groceries', amount: 900, date: new Date(2020, 7, 14)},
{ id:102,title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ id:103,title: 'New Sofa Set', amount: 25000, date: new Date(2021, 2, 28)}
];
function App() {
<div>
{people.map(person => (
<p key={person.name}>{person.name}</p>
))}
</div>
Implementing filters
function App() {
const [expenses, setExpenses] = useState(DUMMY_EXP)
const [filteredYear, setFilteredYear] = useState(2020);
...
const selectYearHandler = filteredValue => {
setFilteredYear(filteredValue)
}
return (
<div className="App">
<h2>Welcome to React!</h2>
<NewExpense onAddExpense={addExpenseHandler} />
<ExpensesFilter onSelectYear={selectYearHandler}/>
{filteredExpensesArr.map(expense => (
<ExpenseItem
key={expense.id}
expDate={expense.date}
expTitle={expense.title}
expAmount={expense.amount}
/>))
}
Rendering content conditionally
• Conditional rendering means to render a specific HTML element or React
component depending on a prop or state value.
In a conditional render, a React component decides based on one or several conditions
which DOM elements it will return.
For instance, based on some logic it can either return a list of items or a text that says
"Sorry, the list is empty".
if(condition_is_met) {
renderSectionOfUI();
}
Rendering content conditionally : example
/*const users = [
{ id: '1', firstName: 'Shrilata', lastName: 'T' },
{ id: '2', firstName: 'Anita', lastName: 'Patil' },
];*/
const users = []
if (!list.length) {
function ListUsers() { return <p>Sorry, the list is empty.</p>;
return ( }
<div>
<List list={users} />
</div> function Item({ item }) {
); return (
} <li>
{item.firstName} {item.lastName}
function List({ list }) { </li>
if (!list) { );
return null; }
} export default ListUsers;
return (
<ul>
{list.map(item => (
<Item key={item.id} item={item} />
))}
</ul>
);
}
Rendering content conditionally : Expense tracker example
//ExpenseForm
<div className="new-expense__actions">
<button type="button"
onClick={props.onCancel}>Cancel</button>
<button type="submit">Add Expense</button>
</div>
CLASS-BASED COMPONENTS
const HelloComponent = (props) => {
Functional components are regular
return (<h3>Hello, welcome user!!</h3>)
javascript functions which return
}
renderable results (typically JSX)
export default HelloComponent;
import './User.css';
import React, {Component} from 'react';
• Initialisation phase:
Constructor(props): This is a special function that is called when new components
are created. In this, we initialize the state or props of the component.
Lifecycle methods
• The mounting phase refers to the phase during which a component is created and
inserted to the DOM.
• The following methods are called in order.
ComponentWillMount(): This function is called immediately before mounting occurs. It
is called right before the first rendering is performed.
render(): You have this method for all the components created. It returns the Html node.
• UnMounting: this state comes into the picture when the Component is not required
or removed.
• Following are the methods available in unmount state:
ComponentWillUnmount(): called when the Component is removed or destroyed.
import React, {Component} from 'react';
this.UpdateName = this.UpdateName.bind(this);
this.testclick = this.testclick.bind(this);
}
UpdateName(event) {
this.setState({name: event.target.value});
}
testclick(event) {
alert("The name entered is: "+ this.state.name);
}
componentDidMount() {
console.log('Mounting State : calling method componentDidMount');
}
shouldComponentUpdate() {
console.log('Update State : calling method shouldComponentUpdate');
return true;
}
componentDidUpdate() {
console.log('Update State : calling method
componentDidUpdate')
}
componentWillUnmount() {
console.log('UnMounting State : calling method
componentWillUnmount');
}
render() {
return (
<div>
Enter Your Name:<input type="text"
value={this.state.name} onChange={this.UpdateName} /><br/>
<h2>{this.state.name}</h2>
<input type="button"
value="Click Here"
onClick={this.testclick} />
</div>
);
}
}
componentDidUpdate(){
if(this.props.users.length == 0)
throw new Error("No users in list!")
}
...
• Error boundaries are React components that catch JavaScript errors anywhere in their child
component tree, log those errors, and display a fallback UI instead of the component tree that
crashed. Error boundaries catch errors during rendering
• https://reactjs.org/docs/error-boundaries.html
• React.Component – React (reactjs.org)
Using Error Boundaries
function App() {
return (
<div className="App">
<h1> Welcome to React</h1>
<ErrorBoundary >
<Person />
</ErrorBoundary>
</div>
);
}
FORMS AND FORMS VALIDATION
Handling user input the right way
Controlled Components and Uncontrolled components
• React forms present a unique challenge because you can either allow the
browser to handle most of the form elements and collect data through React
change events, or you can use React to fully control the element by setting
and updating the input value directly.
The first approach is called an uncontrolled component because React is not setting
the value.
The second approach is called a controlled component because React is actively
updating the input.
state = {
name:'',
onservation:'',
color:'',
size:'',
}
handleChanges = (event) => {
let name = event.target.name;
let val = event.target.value;
this.setState({[name]: val});
console.log(this.state)
};
submitFormHandler = (event) => {
event.preventDefault();
console.log("from submit ", this.state);
};
render(){
const colors = ['Blue', 'Red', 'Green', 'Yellow'];
const sizes = ['Small', 'Medium', 'Large', 'XL', 'XXL', '3XL'];
return (
<form onSubmit={this.submitFormHandler}>
<div className='form-control'>
<label>Name:</label>
<input name="name" type="text" value={this.state.name} onChange={this.handleChanges} />
</div>
<div className='form-control'>
<label>Observation:</label>
<textarea name="observation" value={this.state.observation} onChange={this.handleChanges} />
</div>
<div className='form-control'>
<label>Desired color:</label>
<select name="color" value={this.state.color} onChange={this.handleChanges}>
{colors.map((color, i) => <option key={i} value={color.toLowerCase()}>{color}</option>)}
</select>
</div>
<div >
<label>T-shirt Size:</label>
{sizes.map((size, i) =>
<label key={i}> {size}
<input
name="size" value={size.toUpperCase()} checked={this.state.size === size.toUpperCase()}
onChange={this.handleChanges} type="radio" />
</label>
)}
</div>
<div className="form-actions">
<button type="submit">Submit</button>
</div>
</form>
)}
}
export default MultipleInputFields;
Controlled components : Summary
• A controlled component is bound to a value, and its adjustments will be
handled in code by using event-based callbacks.
Here, the input form variable is handled by the react itself rather than the DOM.
In this case, the mutable state is maintained in the state property and modified using
setState().
• Controlled components have functions which regulate the data that occurs at
each on Change event.
This data is subsequently saved in the setState() method and updated. It helps
components manage the elements and data of the form easier.
•
• You can use the controlled component when you create:
Forms validation so that when you type, you always have to know the input value to
verify whether it is true or not!
Disable submission icon, except for valid data in all fields
If you have a format such as the input for a credit card
Validation
class ControlledInputValidation1 extends React.Component {
state = { age: '' };
Uncontrolled components are inputs that do not have a value property. In opposite
to controlled components, it is the application's responsibility to keep the component
state and the input value in sync.
methodA() {
console.log("methodA in parent class"); Console output
}
render() {
return false;
}
}
function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
// Here we don't use the Context directly, but render children that do.
const AccountSummary = (props) => {
return (
<AccountSummaryHeader/>
<AccountSummaryDashboard/>
<AccountSummaryFooter/>
);
};
All three of these child components may not want to access the current user’s data. But as
an example, let’s just look at the AccountSummaryHeader component:
const AccountSummaryHeader = (props) => {
// Here we retrieve the current value of the context
const context = React.useContext(UserContext);
return (
<section><h2>{context.currentUser.name}</h2> </section>
);
};
Context
• Using context, we can avoid passing props through intermediate elements
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
// A component in the middle doesn't have to pass the theme down explicitly anymore
function Toolbar() {
return (
<div>
<ThemedButton />
</div>
);
}
class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}
Bringing Bootstrap into your React App
• After creating your app project:
• ..Demo\second-app>npm install --save react-bootstrap bootstrap@3
• Then start the app : npm start
render(){
return(
<div className=“container”>
<h1 className="text-danger">TODO LIST </h1>
REDUX
Because state management can be hard
What is state
• Eg: const state = { <div className={this.state.signUpModal.open ? 'hidden' : ''}>
posts: [], Sign Up Modal
signUpModal: { </div>
open: false
}
}
//REDUCER
//DISPATCH
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Create a Redux application
import {createStore} from 'redux’;
• Step-1 : Create the store: const myStore = createStore(reducer-name)
• A reducer is a function that receives the current state and an action object,
decides how to update the state if necessary, and returns the new state:
(state, action) => newState.
You can think of a reducer as an event listener which handles events based on the
received action (event) type.
• The Redux store has a method called dispatch. The only way to update the
state is to call store.dispatch() and pass in an action object.
The store will run its reducer function and save the new state value inside, and we
can call getState() to retrieve the updated value:
My original index.js
//original React imports let store = createStore(counter);
import {createStore} from 'redux';
//Display it in console
//STORE -> GLOBALISED STATE store.subscribe(() =>
console.log(store.getState()));
//ACTION -> INCREMENT
const increment = () => { //DISPATCH
return { store.dispatch(increment());
type :'INCREMENT' //name of the action store.dispatch(decrement());
}
} ReactDOM.render(
const decrement = () => { <React.StrictMode>
return { <App />
type :'DECREMENT' //name of the action </React.StrictMode>,
} document.getElementById('root')
} );
//REDUCER
const counter = (state=0, action) => {
switch(action.type){
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
}
}
//reducers/counter.js
const counterReducer = (state=0, action) => { Create a Redux app
switch(action.type){
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1; //src/index.js
default: return null; import {createStore} from 'redux';
} import allReducers from "./reducers";
}
export default counterReducer; const store = createStore(allReducers);
//reducers/isLogged.js
const loggedReducer = (state=false, action) => {
switch(action.type){
case "SIGNIN": //reducers/index.js
return !state; import counterReducer from "./counter";
default: import loggedReducer from "./isLogged";
return state; import {combineReducers} from 'redux';
}
} const allReducers = combineReducers({
export default loggedReducer; counter : counterReducer,
isLogged:loggedReducer
})
export default allReducers;
//src/index.js
//Original code:
const store = createStore(allReducers);
//New code:
const store = createStore(allReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && windo
w.__REDUX_DEVTOOLS_EXTENSION__());
//src/index.js
import {createStore} from 'redux';
import allReducers from "./reducers"; const counterReducer =
import {Provider} from 'react-redux'; (state=0, action) => {…}
ReactDOM.render(
<React.StrictMode>
<Provider store={myStore}>
<App />
</Provider>
</React.StrictMode>,
App.js : displaying state Allows you to extract data
from the Redux store
state, using a selector
import './App.css'; function.
import {useSelector} from 'react-redux';
function App() {
const counter = useSelector(state => state.counter);
const isLogged = useSelector(state => state.isLogged);
return (
<div className="App"> I set the isLogged
<h1>Welcome to Redux</h1> state to true
<h3>Counter : {counter}</h3>
{isLogged ? <h3> Some valuable info here</h3> : ''}
</div>
);
}
return (
<div className="App">
<h1>Welcome to Redux</h1>
<h3>Counter : {counter}</h3>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
{isLogged ? <h3> Some valuable info here</h3> : ''}
</div>
);
}
export default App;