Skip to main content

React 18 Fundamentals for Sitecore Headless development

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

POPULAR POSTS

Sitecore PowerShell Script to create all language versions for an item from en version

  We have lots of media items and our business wants to copy the data from en version of media item to all other language versions defined in System/Languages. This ensures that media is available in all the languages. So, we created the below powershell script to achieve the same -  #Get all language versions defined in System/Languages $languages = Get-ChildItem /sitecore/System/Languages -recurse | Select $_.name | Where-Object {$_.name -ne "en"} | Select Name #Ensuring correct items are updated by comparing the template ID  $items = Get-ChildItem -Path "/sitecore/media library/MyProjects" -Recurse | Where-Object {'<media item template id>' -contains $_.TemplateID} #Bulk update context to improve performance New-UsingBlock (New-Object Sitecore.Data.BulkUpdateContext) { foreach($item in $items){    foreach($language in $languages){ $languageVersion = Get-Item -Path $item.Paths.Path -Language $language.Name #Check if language versi...

Export Sitecore media library files to zip using SPE

If you ever require to export Sitecore media files to zip (may be to optimize them), SPE (Sitecore Powershell Extension) has probably the easiest way to do this for you. It's as easy as the below 3 steps -  1. Right click on your folder (icons folder in snap)>Click on Scripts> Click on Download 2. SPE will start zipping all the media files placed within this folder. 3. Once zipping is done, you will see the Download option in the next screen. Click Download Zip containing the media files within is available on your local machine. You can play around with the images now. Hope this helps!! Like and Share ;)

Make Sitecore instance faster using Roslyn Compiler

When we install the Sitecore instance on local, the first load is slow. After each code deploy also, it takes a while for the Sitecore instance to load and experience editor to come up. For us, the load time for Sitecore instance on local machines was around 4 minutes. We started looking for ways to minimize it and found that if we update our Web.config to use Roslyn compiler and include the relevant Nugets into the project, our load times will improve. We followed the simple steps - Go to the Project you wish to add the NuGet package and right click the project and click 'Manage NuGet Packages'. Make sure your 'Package Source' is set to nuget.org and go to the 'Browse' Tab and search Microsoft.CodeDom.Providers.DotNetCompilerPlatform. Install whichever version you desire, make sure you note which version you installed. You can learn more about it  here . After installation, deploy your project, make sure the Microsoft.CodeDom.Providers.DotNetCompilerPlatform.d...

Experience of a first time Sitecore MVP

The Journey I have been working in Sitecore for almost 10 years now. When I was a beginner in Sitecore, I was highly impressed by the incredible community support. In fact, my initial Sitecore learning path was entirely based on community written blogs on Sitecore. During a discussion with my then technology lead Neeraj Gulia , he proposed the idea that I should start giving back to developer community whenever I get chance. Just like I have been helped by many developers via online blogs, stackoverflow etc., I should also try to help others. Fast forward a few years and I met  Nehemiah Jeyakumar  (now an MVP). He had a big archive of his technical notes in the form Sitecore blogs. I realized my first blog dont have to be perfect and it can be as simple as notes to a specific problem for reference in future. That's when I probably created my first blog post on Sitecore. At that time, I didn't knew about the Sitecore MVP program. Over the years, I gained more confidence to writ...

Clean Coding Principles in CSharp

A code shall be easy to read and understand. In this post, I am outlining basic principles  about clean coding after researching through expert recommended books, trainings and based on my experience. A common example to start with is a variable declaration like - int i  The above statement did not clarify the purpose of variable i. However,  the same variable can be declared as -  int pageNumber The moment we declared the variable as int pageNumber, our brain realized that the variable is going to store the value for number of pages. We have set the context in our brain now and it is ready to understand what the code is going to do next with these page numbers. This is one of the basic advantages of clean coding. Reasons for clean coding -  • Reading clean code is easier - Every code is revisited after certain amount of time either by the same or different developer who created it. In both the cases, if the code is unclean, its difficult to understand and u...