Ever wish your app could remember things like a user’s theme choice, preferences, or other settings, even after a page reload? Good news: it absolutely can!
With Recoil, your trusty state management tool, and localStorage, the browser’s built-in memory, you can easily persist your app’s state. That means no more resetting the theme or losing data when users refresh or come back later.
And the best part? You don’t need anything complicated. just a few lines of code with Recoil and localStorage. It’s so easy, you’ll wonder why you didn’t do it sooner!
This small tweak makes your app seamless and user-friendly, like it has a memory that syncs with your users.
Ready to add persistence to your app with Recoil? Let’s get started!
First, check out my other blogs on Recoil to get a solid foundation. I cover basics like Recoil Intro Part and Recoil Hooks to help you get the most out of Recoil.
Let’s Implement the State Persistence in Recoil with Local Storage for Theme Preference
import { atom } from 'recoil'; // Atom to store the mode (light or dark) export const modeState = atom({ key: 'modeState', // Unique ID for the atom default: 'light', });
import React, { useEffect } from 'react'; import { useRecoilState } from 'recoil'; import { modeState } from './state'; const App = () => { const [mode, setMode] = useRecoilState(modeState); // Load mode from localStorage useEffect(() => { const savedMode = localStorage.getItem('modeState'); if (savedMode) { setMode(savedMode); // Set the mode if found in localStorage } }, [setMode]); // Save mode to localStorage whenever it changes useEffect(() => { localStorage.setItem('modeState', mode); document.body.className = mode; // Apply the mode to the body class }, [mode]); return ( <div> <h1>Current Mode: {mode}</h1> <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}> Change Mode </button> </div> ); }; export default App;
import React from 'react'; import ReactDOM from 'react-dom'; import { RecoilRoot } from 'recoil'; import './index.css'; import App from './App'; ReactDOM.render( <RecoilRoot> <App /> </RecoilRoot>, document.getElementById('root') );
/* Default light mode */ body.light { background-color: white; color: black; } /* Dark mode */ body.dark { background-color: #121212; color: white; } button { padding: 10px 20px; cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 5px; } button:hover { background-color: #0056b3; }
This app saves and loads the theme from localStorage, and the mode can be toggled between light and dark.
In Inspect Mode (Developer Tools), go to the Application tab to see localStorage entries where the light/dark mode is saved. When the mode is toggled, the localStorage value updates with the new mode. After refreshing the page, the saved mode is retrieved from localStorage and applied, which you can verify by checking both localStorage and the body class in the Elements tab.
In short, using Recoil with localStorage saves user settings like the theme here between sessions and page reloads, making the experience more consistent and personalized.
Using Recoil with localStorage is a win-win for both users and developers. For users, it means their preferences, like the theme, are saved across sessions, making the experience feel seamless and personalized every time they return. For developers, it takes the hassle out of managing state persistence. With Recoil handling the app’s state and localStorage automatically saving settings, developers can focus on building excellent features instead of worrying about saving and loading data. This combination makes the development process smoother, faster, and more efficient.
That’s a wrap for today! But don’t go too far. I’ll be diving into tools and techniques that make development easier and more exciting. Until then, keep experimenting, stay curious, and happy coding!
]]>If you are enjoying using React but find managing state tricky, you need to know about Recoil hooks. They’re made for React developers who want a simpler, more powerful way to handle the state. Let’s jump in and see how it works!
First, we will look at what hooks are in React and their basic definition –
In React, hooks are like unlocking secret abilities for your functional components. They let you add state, perform side effects, and control your app’s lifecycle, all while keeping your code neat and easy to manage and with no classes required!
In my previous blog, we introduced Recoil, covering atoms and selectors and how to create them. Consider this blog as part 2 of the Recoil blog. In this blog, we’ll look at Recoil hooks and see how they can make state management in React easier and more efficient.
Let’s see what the difference is between React hooks and Recoil hooks –
Let’s explore Recoil hooks. These simple hooks manage global state with atoms and selectors, making state handling easy in larger apps. Here’s a quick list:
useRecoilState: This is similar to React’s useState; this hook returns both the current value of an atom and a function to update it. It’s ideal when you need to both read and modify the state.
useRecoilValue: This hook allows you to retrieve the current value of an atom or selector without modifying it. It’s perfect when you only need to read the state and don’t need to trigger updates.
useSetRecoilState: Instead of accessing both the current value and the update function, this hook provides only the function to modify an atom’s value directly. It’s great for situations where you only need to update the state.
useResetRecoilState: This hook resets the atom’s value to its default state, which is useful for clearing or resetting data within your app.
These hooks make it easy to manage state in Recoil, allowing you to read, update, or reset values based on what you need.
Here’s an example to show how these hooks can be used in action –
First, we need to create the Recoil atoms that represent global states, which the components will access and manipulate throughout the application.
import { atom } from 'recoil'; export const counterAtom = atom({ key: 'counterAtom', // unique ID for the atom default: 0, // default value });
This code creates a Recoil atom named counterAtom with a unique identifier (key) and an initial value of 0, allowing the counter’s state to be shared and updated across components using Recoil hooks.
import React from 'react'; import { useRecoilValue } from 'recoil'; import { counterAtom } from '../src/atom'; const Counter = () => { const counter = useRecoilValue(counterAtom); return <div>Counter Value: {counter}</div>; }; export default Counter;
The above code uses the useRecoilValue hook to read the current value of the counterAtom and display it. This hook provides read-only access to the atom’s state in the component.
import React from 'react'; import { useSetRecoilState } from 'recoil'; import { counterAtom } from '../src/atom'; const IncrementButton = () => { const setCounter = useSetRecoilState(counterAtom); return <button onClick={() => setCounter((prev) => prev + 10)}>Increment</button>; }; export default IncrementButton;
Here, we are using the IncrementButton component, which utilizes useSetRecoilState to access a function (setCounter) that updates the counterAtom state. When clicked, the button adds 10 to the counter value using setCounter.
import React from 'react'; import { useRecoilState } from 'recoil'; import { counterAtom } from '../src/atom'; const CounterWithButtons = () => { const [counter, setCounter] = useRecoilState(counterAtom); return ( <div> <div>Counter Value: {counter}</div> <button onClick={() => setCounter(counter + 10)}>Increment</button> <button onClick={() => setCounter(counter - 10)}>Decrement</button> </div> ); }; export default CounterWithButtons;
The CounterWithButtons component uses the useRecoilState hook to get and update the value of counterAtom. It provides the current value (counter) and a function (setCounter) to change the state.
import React from 'react'; import { useResetRecoilState } from 'recoil'; import { counterAtom } from '../src/atom'; const ResetButton = () => { const resetCounter = useResetRecoilState(counterAtom); return <button onClick={resetCounter}>Reset Counter</button>; }; export default ResetButton;
The ResetButton component uses the useResetRecoilState hook to get a function (resetCounter) that resets counterAtom. When the button is clicked, it resets the counter to its initial value.
Recoil makes managing state in React smooth and enjoyable! With hooks like useRecoilValue, useSetRecoilState, and others, it ensures your app’s state stays organized and easy to handle. It’s like having a smart teammate who manages the state while you focus on building the app’s features.
That’s all for today! But stay tuned for more posts on state management libraries that are coming your way to help you take your projects to the next level. Until then, keep experimenting, and happy coding!
]]>Imagine you’re in a library. Redux is like a huge, well-organized library where every book is perfectly categorized, labeled, and placed in its specific spot. It’s ideal for a massive collection, but getting everything in order can take a lot of time. Zustand, on the other hand, is like a comfy reading corner with just a few handpicked books. Everything is right at your fingertips, and you don’t have to spend time organizing it; pick up what you need and enjoy.
In this blog, we’ll explore Redux and Zustand to help you decide which is the perfect fit for your project, whether you’re managing a huge amount of state or just need a few key pieces.
In a previous blog, I explored the essential factors to keep in mind when picking a state management library. Now, let’s take a closer look at what makes Redux and Zustand stand out in this decision-making process.
Each library, whether it’s Redux or Zustand, has its own challenges. Let’s discuss the downsides!
Let’s dive into some code examples to showcase how Redux and Zustand work in action.
Install the packages of Redux by executing the command below:
npm install @reduxjs/toolkit react-redux
Example –
Let’s create a simple counter application using Redux for state management within a React application. Here’s how we can implement it step by step:
Action.js:
export const increment = () => ({ type: 'INCREMENT' }); export const decrement = () => ({ type: 'DECREMENT' });
reducer.js
const counterReducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } }; export default counterReducer;
Store.js
import { configureStore } from '@reduxjs/toolkit'; import counterReducer from './reducer'; // Create Redux store using configureStore const store = configureStore({ reducer: counterReducer }); export default store;
App.js
import React from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { increment, decrement } from './actions'; function App() { const count = useSelector((state) => state); // Access state from Redux store const dispatch = useDispatch(); return ( <div style={{ textAlign: 'center' }}> <h1>{count}</h1> <button onClick={() => dispatch(increment())}>+</button> <button onClick={() => dispatch(decrement())}>-</button> </div> ); } export default App;
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import App from './App'; import store from './store'; // Import the store // Wrap your app with Provider and pass the Redux store ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
To install Zustand –
npm install Zustand
Example –
Store.js
import { create } from 'zustand'; const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })) })); export default useStore;
App.js
// App.js (React Component) import React from 'react'; import useStore from './store'; // Import the Zustand store function App() { // Accessing the state and actions from Zustand store const { count, increment, decrement } = useStore(); return ( <div> <h1>{count}</h1> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); } export default App;
index.js
// index.js (React entry point) import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; // Import the App component // Rendering the App component into the DOM ReactDOM.render( <App />, document.getElementById('root') );
Picking between Redux and Zustand is like choosing between a powerful engine and a smooth ride. Redux offers a ton of features, making it perfect for big, complex applications, but it requires time and effort to learn. Zustand, on the other hand, is the go-to for quick, simple projects, giving you fast setup and ease of use with minimal fuss. Need power and customization? Redux is your choice. Want speed and simplicity? Go with Zustand. Whether you need to build something scalable or just get the job done fast.
In my opinion, the key is understanding your project’s needs. Once you do, you can choose the right tool for smooth development and easy state management.
Pick wisely according to what aligns best with your workflow! That’s it for today, but don’t worry; more posts on state management libraries are coming soon to help you level up your projects. Until then, keep experimenting, and happy coding!
]]>Imagine a world where state management is as simple as it should be. MobX lets you build reactive UIs with zero fuss. Using reactive programming, MobX automatically keeps your UI in sync with your app’s state. There is no need for the boilerplate chaos of actions and reducers. With just a few lines of code, you can make your state observable, and MobX will handle the rest, updating the UI whenever the state changes.
As mentioned in my last blog, MobX is an excellent tool for React developers to manage dynamic data easily. It works behind the scenes, automatically updating the user interface whenever the data changes, so you don’t need to manually handle updates. This makes state management in your app much cleaner and more scalable, especially when dealing with frequently changing data.
MobX is a state management library that ensures your app’s data and UI are always in sync by observing specific parts of your data. Think of it as a helper that watches your app’s data and keeps the UI updated whenever something changes. While it works seamlessly with React, MobX can also be used with other JavaScript frameworks or even in plain JavaScript.
To get started, the first step is to install MobX in your project:
npm install mobx mobx-react
Look at the package.json file, MobX has been installed in our project.
App.js –
import React from 'react'; import { observer } from 'mobx-react-lite'; import store from './store'; const ComponentA = observer(() => { return ( <div> <ComponentB /> </div> ); }); const ComponentB = observer(() => { return <ComponentC />; }); const ComponentC = observer(() => { return ( <div> <p>{store.data}</p> <button onClick={() => store.updateData("Updated the data from Component C")}> Update Data </button> </div> ); }); export default ComponentA;
Component A: Root component. No need to pass data through props
Component B: Directly render Component C (no prop drilling)
Component C: Will directly access the data from the store
Store.js –
import { makeAutoObservable } from 'mobx'; const store = makeAutoObservable({ data: "Welcome to MobX Store", updateData(newData) { this.data = newData; } }); export default store;
Here we are creating a MobX store with an observable data property.
and an updateData action to modify it using makeAutoObservable.
Now just create a root and render the ComponentA to the DOM using ReactDOM. createRoot in index.js.
Let’s sum it up. MobX is used to manage the state with an observable store. The data is made observable in the store, and any component wrapped with the observer function automatically updates when the state changes. The updateData function is an action that modifies the data in the store. When the action is triggered, components that observe the store reactively update and reflect the new data. This setup avoids prop drilling, as components directly access the store, making state management efficient and ensuring the UI stays in sync with the data changes.
Like any other tool, MobX comes with some limitations.
In short, MobX makes state management easy by keeping your app’s data and UI in sync, so you can focus on building features. It only updates the parts of the UI that need it, making things faster and more efficient. With a simple API and automatic updates, MobX helps you create responsive apps without the hassle of managing the state.
That’s it for today! But stay tuned. I’ll be exploring more state management libraries in future posts and showing how they can improve your projects. Until then, keep experimenting, and happy coding!
]]>Have you ever created a React application and ended up struggling with tangled state updates, excessive prop drilling, or overly complex context setups? You’re definitely not alone! As your app scales, managing the state in React can become quite tricky. This is where Recoil comes to the rescue, a powerful new library designed to streamline state management in a way that feels almost like magic.
Don’t worry, though; you don’t need to be a React pro to grasp it. In this blog, we’ll explore what Recoil is and why it could be the perfect solution to help you maintain a clean, efficient, and easy-to-manage app.
In my previous post, I began a detailed exploration of “State Handling Excellence in React,” where we discussed some of the most widely used state management libraries in the React ecosystem.
In my previous blog, we explored Recoil, a state management library created by Facebook that offers a smooth solution for managing the state in React applications. It’s particularly effective for small to medium-sized projects, enhancing React’s built-in functionality with powerful tools that simplify complex tasks. Recoil allows developers to handle the state in a flexible way, tailored to the specific needs of their projects.
In this post, we’ll dive into Recoil’s core features – atoms and selectors, which serve as the foundation for easy and efficient state management.
To get started, the first step is to install Recoil in your project:
npm install recoil
Look at the package.json file, Recoil has been installed in our project.
After setup, Recoil requires the RecoilRoot component at the top level of your app, like how Redux requires the Provider to wrap the application.
import { RecoilRoot } from 'recoil'; ReactDOM.render( <RecoilRoot> <App /> </RecoilRoot>, document.getElementById('root') );
import { Provider } from 'react-redux'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
import { atom } from 'recoil'; export const nameState = atom({ key: 'nameState', default: 'Muskan', });
Here we are creating an atom named nameState in Recoil. It uses the unique identifier ‘nameState’ and sets the default value to ‘Muskan.’ This atom holds data that can be accessed and modified across various components in your app.
Now, let’s move on to another key concept: selectors.
import { selector } from 'recoil'; import { nameState } from './state'; // Importing the atom that holds the name export const nameLengthSelector = selector({ key: 'nameLengthSelector', get: ({ get }) => { const name = get(nameState); // Retrieving the value of nameState atom return name.length; }, });
The nameLengthSelector is a selector that dynamically calculates the length of the string stored in the nameState atom. By utilizing the get function, it fetches the current value of the nameState and computes its length. This approach enables automatic calculation of the name’s length, eliminating the need for manual updates or redundant calculations throughout the app.
In addition to atoms and selectors, Recoil provides several standout features:
These features make Recoil a simple and powerful choice for managing state in React apps.
Recoil makes state management in React simple and efficient. It simplifies managing both global and local state, removes the need for prop drilling, and boosts performance by re-rendering only when necessary. With its easy-to-understand API and clear concepts like atoms and selectors, Recoil is an ideal choice for developers looking for a fast and straightforward way to manage state in React!
That’s a wrap for today! But don’t go too far; I’ll be diving deeper into more state management libraries in future posts, uncovering how they can level up your projects. Until then, keep experimenting, and happy coding!
]]>Handling an application’s state, or state management, plays an essential role in creating dynamic and responsive user interfaces and effectively executing business logic.
React offers numerous state management methods for storing and updating data, making it a popular web development technology.
Think of it like different ice cream flavors: some people like chocolate (Redux), some like vanilla (Recoil), and some like strawberry (MobX). With React, developers can select the flavor that best suits their needs and projects.
React allows developers the flexibility to select how best to organize their code, whether that means keeping things simple using React Hooks or putting everything in one location with Redux.
It is like having a bunch of ice cream toppings; it makes development flexible and enjoyable!
Choosing an appropriate state management library for your React application involves considering various aspects. When making your choice, consider the following crucial factors:
Let’s discuss some of the popular state management libraries and patterns in the React ecosystem:
Let’s dive deeper into these popular state management libraries.
For developers, Redux is like a superhero, especially when they are creating large, complex programs. This amazing tool assists with tracking everything that occurs within your app, much like a superhero watching over the whole city. Redux provides a special store to store all your project data.
The best feature is that no component can just modify things in this store at random; instead, they must notify Redux of what needs to be done by sending a message known as an action. Everything becomes easier to understand and more predictable as the outcome.
One key advantage of Redux is its seamless integration with React, a popular framework in web development. By combining these two technologies, developers can ensure the smooth functioning of their applications and easily address any issues that may arise.
Think of Redux as a reliable guide for managing your app’s state, simplifying the process, and preventing you from getting overwhelmed by its complexity.
Here are some Key concepts in Redux. These concepts work together to establish a structured and predictable framework that ensures systematic management of data flow and application state.
Recoil is an experimental state management library developed by Facebook that provides a powerful solution for handling states in React applications, particularly for small-to-medium-sized projects.
It enhances the capabilities of the basic React framework and offers a group of features that can be tough to accomplish with React alone.
Recoil’s flexibility and adaptability in managing state are key advantages, especially when dealing with components. It allows developers to handle the state in ways that meet a project’s specific needs.
Recoil simplifies managing data in React, making complex state handling effortless. It is like having a handy tool that takes the stress out of managing your application’s data.
For more information about Recoil, you can check out my upcoming blog.
The introduction of React Hooks in React version 16.8 in February revolutionized state management in functional components. Before Hooks, the handling state of functional components was limited, and class components were mainly used.
The useState Hook is the primary component of Hooks, allowing simple state management within functional components.
Furthermore, react offers additional Hooks for particular use cases and advanced functionality, enhancing the overall development experience and increasing state management flexibility.
Below are a few of the most used React hooks for state management.
A built-in feature of React called the Context API makes it easier to maintain a local state within a component tree and allows the state to be shared globally without having to be explicitly sent down through props.
It is frequently used to update and provide easy access to states for components located further down the component tree and to manage states at higher levels of the component tree.
It was made with createContext and comes with a provider and a consumer for sharing state management.
Supplier: wraps components to provide context.
Consumer: Accesses the component’s context value.
Default Values: Provides a default value for components outside a provider’s scope when the context is created.
Nested Contexts: Allows the nesting of multiple contexts, each with a separate provider and consumer.
Dynamic Context Updates: This enables the context value to be updated dynamically based on the component’s logic or state.
Performance Optimization: Optimizes rendering and avoids needless re-renders using techniques such as React. Memo.
React developers can use MobX, a useful tool, to manage the dynamic data in their projects. Like a manager operating in the background, it ensures that the user interface (the user interface) updates automatically when data changes.
It is beneficial for clean, scalable state management for your app.
It simplifies the process of tracking changing data, which is essential in React. MobX lets you specify certain areas of your data (or state) to be tracked and updates the display whenever those parts change.
MobX is a helpful utility that monitors the data in your app and ensures that everything remains coordinated without requiring you to update the UI (User Interface) manually whenever something changes.
It is a clever approach to dealing with React application state management problems.
You can refer to the official MobX documentation at https://mobx.js.org/ for further information and advanced usage.
Zustand is a helpful tool for React, making it easier to manage and control the data in your applications.
It is known for being straightforward and not overly complex, yet despite this, it still has a lot of powerful features for managing how things are stored and updated in React.
It functions similarly to a straightforward and reliable helper in managing the data in your application. It is a lightweight yet powerful alternative to other state management solutions like Redux or MobX.
Below are a few key points about Zustand worth noting.
For React apps, Jotai is a simplified state management solution that offers an option to more well-known tools like Redux and Context API. Its easy-to-use API and lightweight design make it attractive for developers looking for a simple state management solution.
Jotai is made to work well with small or big applications and is easy to integrate into projects. It has a cool feature called atoms and derived atoms that make handling state simple and improve the overall development experience.
With a focus on simplicity, Jotai presents a concise API, unveiling just a few exports from its main bundle.
Atom’ is used to create fundamental states without assigned values, and ‘useAtom’ helps in managing states within React components. ‘createStore’ is the core of state management in Jotai, acting as a pivotal point.
The ‘Provider’ connects components, enabling the sharing of state details and simplifying communication across various project parts. This approach indeed offers a straightforward method for managing state in React applications.
In summary, React provides a variety of state management libraries to cater to different requirements. Whether you value Redux for its established dependability, MobX for its simplicity, or Recoil for its contemporary approach, every project has an option. The crucial aspect is to select the most suitable option for your project and what your team is comfortable with. By thoroughly evaluating the factors mentioned in the blog, you can confidently opt for the most appropriate state management solution for your React applications.
Here are the official websites where you can find more information about the state management libraries and React features we discussed.
Redux: https://redux.js.org/
Recoil: https://recoiljs.org/
React Hooks: https://reactjs.org/docs/hooks-intro.html
Context API: https://reactjs.org/docs/context.html
MobX: https://mobx.js.org/README.html
Zustand: https://github.com/pmndrs/zustand
Jotai: https://github.com/pmndrs/jotai
Plus, stay tuned for my upcoming blogs to dive deep into the world of state management!
]]>In this blog, we will explore generics in TypeScript, but before diving into generics, let’s first understand what TypeScript is and why TypeScript has become increasingly popular in the software development industry.
TypeScript, as a free and open-source high-level programming language, acts as a superset of JavaScript by introducing features like interfaces, enums, and type annotations.
Its main benefit is that it can discover errors early in the development process, identifying potential problems and data types before the code is executed. This proactive strategy helps developers prevent runtime errors and improves code predictability.
The flexibility of TypeScript is a major characteristic, and features like generics and union types are essential. To make the most of TypeScript’s flexibility, it’s important to know the distinctions between union types and generics. These features improve TypeScript’s efficiency in handling types.
In TypeScript, generics enable you to write code that can work with various data types without specifying them in advance, unlike unions, where specific types must be predefined. Generics specify the data type when the code is executed, providing greater adaptability and abstraction than unions.
Type Safety: By providing type safety at compile-time in this statically typed language, generics provide a way to write flexible code while supporting type safety.
Reusability of Code: Generics make it possible to write flexible, reusable code for a variety of types, which minimizes duplication and improves maintainability.
Better Maintainability and Readability: Generics allow writing code that conveys meaning without being restricted to specific types, which results in more maintainable and readable code with clear and flexible logic for various situations.
So, let’s see the syntax of generics:
This TypeScript code defines a generic function named message that takes an input of any type (T) and returns the same type. The function is then used twice, first with a string input (“Hello, typescript!”) and second with a number input (123456).
The generic function ensures type safety, allowing the returned values to maintain their original types. The resulting output successfully uses the generic function with string and number inputs, printing “Hello typescript!” and 123456, respectively.
The above example is created to swap the values of two variables while supporting type safety. It accepts two parameters of the same generic type, T, and swaps the values in a tuple [T, T].
In the above examples, the result of switching the numerical values 50 and 100 are stored in ReverseNumbers, giving the output [100, 50].
Similarly, ReverseString performs swapping of the string values “hello” and “generics,” producing the result [“generics”, “hello”].
Because of its generic nature, the function can handle a variety of data types while ensuring type correctness, making it versatile and reusable for value swapping.
The following illustration shows what TypeScript does when you call a generic function, such as message<T> (input: T): T and pass it as a string.
In conclusion, enhancing TypeScript code with generics empowers flexible coding. Add them to your next code to make it more flexible and reusable and to ensure type safety while working with a variety of data types.
Thanks for reading!
]]>In the last blog, we get to know about how to create a component in the site studio.
In this blog, we are going to set up the component form builder for the component.
You can improve specific functionalities or enhance the visual appearance of your site by using component form builder. The component form builder is located below the layout canvas. To add fields to your Component forms, use Field elements. It can be built by clicking the plus button similar to the layout above with using fields instead of elements.
Firstly, we need to add the tab container
Click on the plus button, first search for Tab Container from fields in the Sidebar browser, and drag and drop into the form builder.
Now choose Tab item fields and wrap them inside the Tab container. Renamed the tab item fields as Content.
In the content field, you can add the text and image content inside this field, then add the field group inside it.
Also, by double-clicking on the field, you get to choose the Default state of the field as well as we have the settings of Visibility. Depending on the conditional logic placed into the field’s “Show field if” input, component form fields can be shown or hidden.
Now we need to connect fields with the correct element, so double click on the Heading element from the layout canvas, then switch to toggle variable mode. Simply type the name of the field in the square bracket as shown in the below image. To switch out of variable mode, click the plus sign, it will return every field to its original form.
Also, add Field label and Machine name on form fields.
Second, is the Layout and Style, here we need to add the stylings for components, for ex – Background color, border, outer padding, and Text / Image alignment which will be editable in the component, then do add the same above steps to enter tokens into the form fields.
And last is the Help, in this tab, we can add information or uses about the form elements, and this tab is totally optional.
And lastly, preview your component form in the Component form preview area to see how the form has been created.
Thanks for Reading!
]]>Site Studio is a Drupal product from Acquia which builds a low-code and component-based website with a simple drag-and-drop interface.
So, what is a component? Components are the mini templates to provide a flexible layout system to customize each section on the page as per requirements. This can be used by site builders in pages to create component-based layouts.
Components can also be used by site builders in templates to take a component-based approach to create websites. This is a reusable object it can be used multiple times with different content on the pages. We can easily drag and drop these site studio components to create pages on websites.
Step 1 – First, navigate to the Site studio menu from the admin menu, Site Studio -> Components -> Components –> and click on Add components.
Step 2 – Then, we need to fill in the details of our components. Add Component Title, choose a category to which category it belongs to, and add Preview image, which is a thumbnail in the sidebar browser.
Tip: There are some component naming conventions we need to take into consideration
Step 3 – Next, we have the layout canvas, layout canvas is a drag-and-drop interface for structuring layouts. Here we build our layout of the component by using the Elements.
Site Studio provides diverse types of drag-and-drop elements which are:
For more information about using these Elements, you can refer to this Document
Now, click on the “+ plus” button and drag and drop the elements according to your component.
First, drag the Layout elements inside it.
Step 4 – Now comes the styling part, by using the style tab, you can give stylings to your component. Double-click on the element and you can see all the settings.
In the properties tab, you can get all the CSS styles as well as we have the option of custom CSS.
Tip: Better to use a full-width container first and a boxed-width container to center rather than using any CSS stylings to center the component.
Step 5 – Next, we need to add the actual content element. Add the elements from the sidebar browser according to your component, here also you can add the styling from the properties tab by double-clicking on the elements.
Step 6 – Now, create the component form, and preview your component form in the Component form preview area to see how the form has been created. And save it as a component by simply clicking “Save and continue.”
For more information about the component form builder, you can check my upcoming blog on the Component form builder.
Step 7 – Add your component to a page that has a Layout canvas. Now, drag and drop it into the layout and double-click on the Component to edit its settings and add the content inside it.
Lastly, Save and Preview your page. And now your Site Studio component is ready.
Thanks for reading!
]]>