What problems does React help to solve?
It is a JavaScript library to build UI. HTML is good for Static UIs. For SPA, UI needs to dynamic. Though it can be done using JS, but JS is difficult to manage.
React brings structure with components.
How React Helps to develop an application?
React helps to create hierarchies of reusable components. It helps to create features around components.
What are core React Features?
1. Structure with components to help reusability and assign state.
2. React helpts to declare UIs in JS. This enables to to allow rendered output to change when state is updated.
3. React is efficient. It uses reconciliation and only updates the parts of the UI that changes.
What is the Anatomoy of a React Application?
A component looks like below -
const Banner = () => <h1>This is a banner </h1>
Components are JS functions that return JSX (Javascript Extension). JSX looks like HTML but it isnt. It is an alternative way to write Javascript.
Browser does not understand JSX. Babel is used to convert JSX to Javascript so that browser understands it.
If you provide JSX to Babel, it can convert it to a proper Javascript. Check snapshot below -
Each time browser needs to render a component, ReactDOM uses the create element to generate HTML elements for the browser.
Here is another component which reuses a component -
const Greeting = () => (
<div>
<Banner />
<h2 className="highlight">Greetings!!</h2>
</div>
);
* className - an equivalent of class attribute in HTML
Above component will get converted by Babel into a javascript as in snapshot below -
Class Components
An alternative way to write compnents is using class as in code below -
class Greeting extends React.Component {
render(){ -- returns JSX
return (
<div>
<Banner />
<h2 className="highlight">Greetings!!</h2>
</div>
)
}
}
Note - It is recommended to create components as function. New future react features are only available in functions. Functions are less verbose and easy to manage.
Tools For React Application
Tools provide -
-starting point for application
-transform jsx to javascript
-process javascript files
-run development server
-automatically update browser when source files change
-create a production build
A developer can configure tools themselves but it require knowledge and time.
A developer can go for a ready-to-go app which has everything out of the box like
create-react-app
or next js.
In this example, we will use next.js.
React!=Next.js
React is js lib where next.js provide ready to go tooling.
Setting up your React App
Steps
1- Install Node.js
2. Open command prompt and run command to create next app -
What are modules?
Module in a reactjs app is a js file defining a module. The export keyword exports the function to be used by the other modules in the app.
const doSomething = () =>{
....
};
export {doSomething}
another modules use import keyword to import other modules -
import {doSomething} from './module';
doSomething();
Modules can export a default member using default keyword. Module that import such modules dont hv to specify method name within curly braces then -
Why to use modules?
Code Structure
Reusability
Encapsulation - anything not exported from module is private
Needed for bundling - without modules, bundling tools will have no idea of modules.
It is good practice to keep only one component each file and name the file with the component name.
Props
Props are used in ReactJS to pass arguments into the components. Sitecore uses the props to pass data based on rendering datasource to a component in ReactJS that represents a rendering in Sitecore.
This simply means if you need to access datasource item values for a rendering on a page in Sitecore, you should be working with props.
For e.g. In below snapshot, headerText is being passed to Banner component via props -
Banner component will consume the headerText via props as shown in snapshot below -
React Fragments
JSX return from a component can only have one parent element.
for e.g. return (
<div>
<div></div>
<div></div>
</div>
)
Sometime empty divs are added just to comply with the requirement and such divs add empty div in final HTML.
In such case, React fragments can be used which can be mentioned as
return (
<React.Fragment>
<div></div>
<div></div>
</React.Fragment>
)
or short hand version for it is -
return (
<>
<div></div>
<div></div>
</>
)
Arrays
If there is an array for e.g. const numbers = ["one", "two", "three"];
then this can be parsed using map function -
const numberPrefixed = numbers.map(n=>"Number"+n);
Key Prop
Items are usually removed/added to array. This changes the order/size of the array elements. There shall be a way to add a key to each item in array so that each item is identifiable using its key.
Hooks
A hook is a function. Built in hooks helps use React built in components.
Starts with use
encapsulates functionality
Built in hooks helps to use react internal features
custom hooks can be created which can be imported in components
Rules
Hooks are only called at top level
Hooks can only be called functions.
Most commonly used hooks is state.
State
State is the data kept internally by component.
Why do we need state?
When we render data, we write JSX to generate HTML.
If we need to add a row to table, we add data to an array. Table that is rendered is reflection of the array that contains data. When data is added to array, react acan not know that table is updated.
To fix it, we need states.
Here is how we use it -
const [houses, setHouses]= useState(houseArray);
useState - inbuilt hook, take initial value as parameter, returns array with current value and fucntion to change it (the set function)
houseArray - data array passed to the hook to trak
const[houses, setHouses] - object that represents state, function used to change the state
A prop value can change
Prop for one component can be state for other component.
Component Rendering
When the state of component is changed, component function is executed again and it is re-rendered.
React uses states internally by storing them in in-memory arrays.
React.Memo
React.memo can be used to cache react components. It shall always be used when it is faster. Use profiling tools to check this. It shall only be used with Pure Fucntions (functions that return same response when provided same inputs)
Effects
API interaction etc. are not pure functions. For such functions, effects are used.
useEffect(()=>{
const fetchHouses = async () = >{
const response = await fetch("api url ");
const houses = await response.json();
setHouses(houses);
};
fetchHouses();
},[]); --empty array at end is dependency injection to ensure useEffect run only at component initialization
usememo hook
const result = useMemo(()=>
{return timeConsumingCalc(houses);
}, [houses])
Ref hook
Modifying a ref hook does not cause a re-render
const counter = userRef(0);
Conditional Rendering and Shared State
Conditinally apply anything
if(house.price<50000)
priceTd =
else
...
{house.price && ( -- if house.price is not 0 or null
<div>fdfsfs</div>
)
}
This is also possible -
Passing Function as props
Comments
Post a Comment