<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Berkay Sonel</title>
    <description>The latest articles on Forem by Berkay Sonel (@berkaysson).</description>
    <link>https://forem.com/berkaysson</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1114669%2F47f70645-447b-49b5-b9c3-634c057db1e4.jpeg</url>
      <title>Forem: Berkay Sonel</title>
      <link>https://forem.com/berkaysson</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/berkaysson"/>
    <language>en</language>
    <item>
      <title>A Clean React Folder Structure</title>
      <dc:creator>Berkay Sonel</dc:creator>
      <pubDate>Sat, 09 May 2026 11:38:07 +0000</pubDate>
      <link>https://forem.com/berkaysson/a-clean-react-folder-structure-4nbh</link>
      <guid>https://forem.com/berkaysson/a-clean-react-folder-structure-4nbh</guid>
      <description>&lt;h1&gt;
  
  
  A Clean React Folder Structure
&lt;/h1&gt;

&lt;p&gt;When building a React app, having a well-organized folder structure makes everything easier finding files, maintaining code, scaling your app, and onboarding new developers. Here's a folder layout that's worked well for many teams, with a quick explanation of what each folder does.&lt;br&gt;
You don’t need to use each folder but while scaling the app with time it is easier to adapt project with this type of folder structure. &lt;/p&gt;

&lt;h2&gt;
  
  
  Folder Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/
│
├── api/
├── auth/
├── components/
├── constants/
├── types/
├── hooks/
├── layouts/
├── locales/
├── mock/
├── pages/
├── queries/
├── routes/
├── sections/
├── services/
├── store/
├── theme/
└── utils/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Folder Descriptions
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;mock/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
This folder is where you put mock data used for development or testing. It's great for simulating backend responses before your API is ready. You can define dummy blog posts, user data, or any sample content you might need during development.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;api/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Here, you set up your Axios instance and define global configuration like base URLs or interceptors. It's the central place where all your HTTP setup lives, separate from the actual request functions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;auth/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Handles everything related to authentication. This includes storing tokens, managing login/logout logic, and setting up user context. Basically, anything that keeps track of whether the user is logged in and who they are.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;components/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Contains shared, reusable UI components like buttons, inputs, modals, form fields, etc. These are your building blocks, used across different parts of the app.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;constants/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Stores fixed values you might need throughout your app, like dropdown options, role lists, or status values. Unlike mock data, these are not just for testing they're actual values your app depends on.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;types/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
If you’re using TypeScript, this folder is great for storing global type definitions, enums, and interfaces (instead of scattering them in random files).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;hooks/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
A place for custom hooks that solve specific problems or add features to your components. Examples: &lt;code&gt;useClipboard&lt;/code&gt;, &lt;code&gt;useResponsive&lt;/code&gt;, or a custom &lt;code&gt;useDebounce&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;layouts/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
This folder contains layout components like sidebars, headers, footers, and wrappers for different page types. It’s useful when you have multiple layout variations like admin and public views or different types of navigations.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;locales/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Used for managing translations and locale-related settings. You can also store dayjs or MUI date adapters, language contexts, and other internationalization (i18n) logic here.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;pages/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Similar to Next.js or other router-based setups, this defines the structure of your app’s pages. However, these files are lightweight and don’t contain full page content just the route presence and sometimes minimal setup. Actual content is handled in the &lt;code&gt;sections/&lt;/code&gt; folder. This way it is easier to scale your app with increasing number of pages.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;queries/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
If you're using &lt;a href="https://tanstack.com/query" rel="noopener noreferrer"&gt;TanStack Query (React Query)&lt;/a&gt;, this is where you'd keep your query and mutation hooks. It helps to organize your data-fetching logic and caching in one place.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;routes/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Here you define your app’s routes using React Router (or another router). You can also manage role-based access, lazy loads and navigation guards here. It connects what's in &lt;code&gt;pages/&lt;/code&gt; to the actual routing setup.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;sections/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
This is where the actual content of each page is built. You compose your &lt;code&gt;components/&lt;/code&gt; inside &lt;code&gt;sections/&lt;/code&gt; to create the structure and logic of each page from pages with creating folders for each page, you can create views to contain all other blocks and use it in pages. It keeps your &lt;code&gt;pages/&lt;/code&gt; clean and focused just on routing for larger apps.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;services/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Contains simple functions that call your API using the Axios instance from &lt;code&gt;api/&lt;/code&gt;. For example, &lt;code&gt;postBlogPost(data)&lt;/code&gt; or &lt;code&gt;getUserInfo()&lt;/code&gt;. Think of this as the layer between your UI and the backend. You can use this services in queries/.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;store/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
If you’re using a state management library (Redux, Zustand, Recoil, Jotai, etc.), keep your global stores, slices, and related logic here. This prevents mixing state with hooks/.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;theme/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Stores your theme setup color schemes, typography, spacing, fonts etc. It can include your MUI theme, dark/light mode settings, and theme providers.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;utils/&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
General utility functions that help with common tasks like formatting dates, validating input, or converting values. These are often small, pure functions reused throughout the app.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Using this structure keeps your project clean, modular, and easy to grow. It separates responsibilities well, so you're not stuffing everything into one or two folders. You can tweak it to fit your team’s style, but this setup is a solid starting point for most medium to large React projects.&lt;/p&gt;




</description>
      <category>architecture</category>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Building an Authentication Starter: Lessons from Integrating Next.js, PostgreSQL, Prisma, and NextAuth</title>
      <dc:creator>Berkay Sonel</dc:creator>
      <pubDate>Sat, 09 May 2026 11:36:14 +0000</pubDate>
      <link>https://forem.com/berkaysson/building-an-authentication-starter-lessons-from-integrating-nextjs-postgresql-prisma-and-2hfg</link>
      <guid>https://forem.com/berkaysson/building-an-authentication-starter-lessons-from-integrating-nextjs-postgresql-prisma-and-2hfg</guid>
      <description>&lt;h1&gt;
  
  
  Building an Authentication Starter: Lessons from Integrating Next.js, PostgreSQL, Prisma, and NextAuth
&lt;/h1&gt;

&lt;p&gt;When starting a new web project, setting up user authentication can often feel like a significant initial friction. There are many components involved: managing user data, securing routes, handling different login methods, and keeping everything type-safe. My goal was to create a solid starting point for future projects, something that handles these complexities without requiring extensive setup each time. This led me to develop a Next.js authentication starter app, and I'd like to share some insights from the process.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Foundation: Why These Technologies?
&lt;/h2&gt;

&lt;p&gt;The project is built on a few core technologies, chosen for their individual strengths and how well they work together. These technologies also promising and future proof.&lt;/p&gt;

&lt;h3&gt;
  
  
  Next.js
&lt;/h3&gt;

&lt;p&gt;I chose &lt;strong&gt;Next.js 14&lt;/strong&gt; as the application framework. Its App Router structure makes route definition and data fetching much clearer, especially for server-side rendered applications. It offers a modern approach that simplifies many common web development tasks.&lt;/p&gt;

&lt;h3&gt;
  
  
  PostgreSQL &amp;amp; Prisma
&lt;/h3&gt;

&lt;p&gt;For data management, I implemented for &lt;strong&gt;PostgreSQL&lt;/strong&gt; and &lt;strong&gt;Prisma&lt;/strong&gt;. PostgreSQL is a widely used relational database, known for its stability. Prisma, as an ORM, significantly simplifies database interactions. It provides a type-safe way to define models and perform queries, which was a huge win for developer experience and reducing potential bugs. Defining my database schema in &lt;code&gt;prisma/schema.prisma&lt;/code&gt; and using Prisma migrations felt a natural fit for managing changes.&lt;/p&gt;

&lt;h3&gt;
  
  
  NextAuth.js
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;NextAuth.js&lt;/strong&gt; handles the core authentication logic. It abstracts away much of the complexity of session management, social logins (like Google and GitHub), and callback handling. Configuring it in &lt;code&gt;auth.config.ts&lt;/code&gt; allowed me to define providers and custom callbacks easily.&lt;/p&gt;

&lt;h3&gt;
  
  
  Additional Tools
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Resend&lt;/strong&gt;: For sending emails related to verification and password resets. This was chosen for its developer-friendly API.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Tailwind CSS &amp;amp; ShadCN&lt;/strong&gt;: To get a user interface up and running quickly. Tailwind CSS helps with rapid styling, and ShadCN provides a collection of accessible components built on top of it.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Zod&lt;/strong&gt;: For form validation. Defining schemas in &lt;code&gt;schemas/&lt;/code&gt; made sure my data inputs were always correctly formatted and type-safe, preventing many common form-related issues.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;bcryptjs&lt;/strong&gt;: For password encryption, a crucial security measure.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Key Features I Focused On
&lt;/h2&gt;

&lt;p&gt;This starter app includes several features designed to cover common authentication needs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;User Forms&lt;/strong&gt;: Login, verification, update password, reset password and registration pages, supporting both email/password and social logins (Google, GitHub).&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Protected Routes&lt;/strong&gt;: Implementing &lt;code&gt;middleware.ts&lt;/code&gt; to check user sessions before allowing access to specific parts of the application, like &lt;code&gt;/settings&lt;/code&gt;. The user should add his/her application pages to here.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Email Verification &amp;amp; Password Reset&lt;/strong&gt;: Generating secure tokens and using Resend to send emails for these critical flows.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Data Handling&lt;/strong&gt;: A clear separation between &lt;code&gt;actions/&lt;/code&gt; for database mutations and &lt;code&gt;data/&lt;/code&gt; for read operations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How the Project is Organized
&lt;/h2&gt;

&lt;p&gt;Understanding the project's layout was important for building it and will be for anyone extending it.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;app/&lt;/code&gt;&lt;/strong&gt;: Contains all route definitions, including public routes like &lt;code&gt;/&lt;/code&gt; and &lt;code&gt;/auth/login&lt;/code&gt;, and protected routes like &lt;code&gt;/(protected)/settings&lt;/code&gt;. App router.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;actions/&lt;/code&gt;&lt;/strong&gt;: Where server actions live, connecting to the database for operations like creating a new user or updating a profile.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;data/&lt;/code&gt;&lt;/strong&gt;: Functions for fetching data from the database, typically read-only.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;components/&lt;/code&gt;&lt;/strong&gt;: My reusable UI elements, keeping the interface consistent.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;lib/&lt;/code&gt;&lt;/strong&gt;: General utilities and helpers.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;prisma/&lt;/code&gt;&lt;/strong&gt;: Holds the Prisma schema and generated client for database models and migrations.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;schemas/&lt;/code&gt;&lt;/strong&gt;: All Zod validation schemas, ensuring data integrity.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;middleware.ts&lt;/code&gt;&lt;/strong&gt;: Handles route protection and authentication checks.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;auth.config.ts&lt;/code&gt;&lt;/strong&gt;: NextAuth configuration details, including providers and callbacks.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Insights and Lessons Learned
&lt;/h2&gt;

&lt;p&gt;One of the main takeaways from putting this together was the power of explicit data validation with Zod. It really helped to catch errors early and provided clear feedback for form inputs. Separating concerns between &lt;code&gt;actions/&lt;/code&gt; and &lt;code&gt;data/&lt;/code&gt; also made the server-side logic much easier to reason about and maintain as the project grew. User can use tanstack query or useSwr for data fetching, starter pack enables every possible way that user can go.&lt;/p&gt;

&lt;p&gt;Thinking about alternatives, I considered different ORMs like neon, but Prisma's type-safety with TypeScript was a strong argument for its use and also very easy to use, I found that Neon is another powerful alternative but for a starter kit it was too much like raw SQL. For email sending, there are many options, but Resend's API worked well for integrating token generation. These parts very easy to change and use alternative.&lt;/p&gt;

&lt;h2&gt;
  
  
  Concluding Thoughts
&lt;/h2&gt;

&lt;p&gt;This Next.js authentication starter project is designed to offer a solid starting point for applications needing user authentication. It brings together well-regarded tools to handle many common challenges. If you're looking to kickstart a project with Next.js 14 and need a reliable authentication setup, feel free to explore it. I'm always open to hearing about different approaches or improvements!&lt;/p&gt;

&lt;h3&gt;
  
  
  Repo:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/berkaysson/nextjs-auth-starter" rel="noopener noreferrer"&gt;Next.js Auth Starter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>nextjs</category>
      <category>postgres</category>
      <category>security</category>
      <category>webdev</category>
    </item>
    <item>
      <title>React States Are Asynchronous, But!</title>
      <dc:creator>Berkay Sonel</dc:creator>
      <pubDate>Sat, 09 May 2026 11:33:30 +0000</pubDate>
      <link>https://forem.com/berkaysson/react-states-are-asynchronous-but-4ol</link>
      <guid>https://forem.com/berkaysson/react-states-are-asynchronous-but-4ol</guid>
      <description>&lt;p&gt;🧠 &lt;strong&gt;State Updates In React Are Asynchronous, But Not Promise!&lt;/strong&gt;&lt;br&gt;
Many developers working with React realize it over time, but it can be confusing at first:&lt;br&gt;
&lt;code&gt;setState&lt;/code&gt; (or &lt;code&gt;setX&lt;/code&gt; with &lt;code&gt;useState&lt;/code&gt;) functions &lt;strong&gt;work asynchronously, but do not return Promise.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What does this mean?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;count&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setCount&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nf"&gt;setCount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;count&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;count&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Still the old value!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we may think that &lt;code&gt;count&lt;/code&gt; value has increased immediately, but React batches this update and saves it for the next render. So &lt;code&gt;console.log(count)&lt;/code&gt; still prints the old value. This shows us the following:&lt;/p&gt;

&lt;p&gt;➡️ &lt;code&gt;setState&lt;/code&gt; is triggered but not applied immediately.&lt;br&gt;
➡️ We cannot use &lt;code&gt;.then()&lt;/code&gt; like a Promise.&lt;br&gt;
➡️ If we want to access the updated state, we have to use methods like &lt;code&gt;useEffect&lt;/code&gt; or the state function with callback.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nf"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;((()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Count changed:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;count&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;count&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nf"&gt;setCount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So the expression &lt;strong&gt;asynchronous but not promise&lt;/strong&gt; comes into play here. React updates the state according to its internal planning, but it doesn't give us a promise. 🔁&lt;/p&gt;

&lt;p&gt;Knowing this difference is very important to avoid making mistakes, especially in form operations, animations or state-dependent business logic. 👨‍💻&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to Create Beatiful Snackbar Component with Material UI + React + CSS in sx🤔</title>
      <dc:creator>Berkay Sonel</dc:creator>
      <pubDate>Mon, 10 Jul 2023 14:04:04 +0000</pubDate>
      <link>https://forem.com/berkaysson/how-to-create-beatiful-snackbar-component-with-material-ui-react-css-in-sx-1a67</link>
      <guid>https://forem.com/berkaysson/how-to-create-beatiful-snackbar-component-with-material-ui-react-css-in-sx-1a67</guid>
      <description>&lt;p&gt;&lt;strong&gt;Snackbar components&lt;/strong&gt; play a crucial role in providing feedback and notifications to users in a visually appealing and non-intrusive manner. With the power of Material-UI and React, we can create stunning and customizable snackbars that integrate into our applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites:
&lt;/h2&gt;

&lt;p&gt;To follow along with this tutorial, you should have a basic understanding of React and have Material-UI installed in your project. Make sure you have set up your development environment (I suggest to use create-react-app) before proceeding.&lt;br&gt;
You have to install Material UI components:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @mui/material @emotion/react @emotion/styled
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Let's start with a simple MUI Snackbar component:
&lt;/h3&gt;

&lt;p&gt;First, we import the Snackbar component from Material-UI using the following import statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Snackbar from "@mui/material/Snackbar";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we define our functional component, which will return the MUI Snackbar component with the necessary state and functions. The state variable &lt;strong&gt;open&lt;/strong&gt; manages the visibility of the snackbar, and the &lt;strong&gt;handleClose&lt;/strong&gt; function is responsible for closing the snackbar. Here's an example of how the component may look:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import Snackbar from '@mui/material/Snackbar';

const MySnackbar = () =&amp;gt; {
  const [open, setOpen] = useState(false);

  const handleClose = (event, reason) =&amp;gt; {
   // this condition will prevent dissapering Snackbar when clicking away
    if (reason === 'clickaway') {
      return; 
    }

    setOpen(false);
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={()=&amp;gt;setOpen(true)}&amp;gt;Activate Snackbar&amp;lt;/button&amp;gt;
      &amp;lt;Snackbar 
       open={open} 
       onClose={handleClose} 
       autoHideDuration={4000}
       message="Hello World!"
      /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default MySnackbar;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, let's break it down:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We have the &lt;strong&gt;&lt;em&gt;open&lt;/em&gt;&lt;/strong&gt; state variable that manages the &lt;strong&gt;&lt;em&gt;open&lt;/em&gt;&lt;/strong&gt; prop of the Snackbar component. By updating the &lt;strong&gt;&lt;em&gt;open&lt;/em&gt;&lt;/strong&gt; state, we control whether the Snackbar is visible or not.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The button there for just to make &lt;strong&gt;&lt;em&gt;open&lt;/em&gt;&lt;/strong&gt; state true so we can see our Snackbar.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;strong&gt;&lt;em&gt;onClose&lt;/em&gt;&lt;/strong&gt; prop of the Snackbar component is handled by the &lt;strong&gt;&lt;em&gt;handleClose&lt;/em&gt;&lt;/strong&gt;function. This function takes two arguments: event and reason. When the Snackbar is closed, we check the reason. If the reason is &lt;em&gt;'clickaway'&lt;/em&gt;, indicating that the user clicked away from the Snackbar, we don't close it. This prevents the Snackbar from disappearing unintentionally.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;To determine when the Snackbar should automatically close, we use the &lt;strong&gt;&lt;em&gt;autoHideDuration&lt;/em&gt;&lt;/strong&gt; prop. This prop defines the duration, in milliseconds, for which the Snackbar will be displayed before automatically closing. In our example, the Snackbar will be shown for 4000 milliseconds (4 seconds) before it closes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Lastly, we have the &lt;strong&gt;&lt;em&gt;message&lt;/em&gt;&lt;/strong&gt; prop, which sets the text content that will be displayed in the Snackbar.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's look our Snackbar:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhnxn5cuo8z4tmq7dl8d0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhnxn5cuo8z4tmq7dl8d0.png" alt=" " width="800" height="496"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It is not the best looking Snackbar 🙄, but we can change it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Styling Snackbar
&lt;/h3&gt;

&lt;p&gt;We have the ability to customize the style of its elements using the sx prop. However, the interesting part lies in our desire to specifically style the SnackbarContent component. SnackbarContent is a component provided by Material-UI that is used as the content container within the Snackbar component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Snackbar 
       open={open} 
       onClose={handleClose} 
       autoHideDuration={4000}
       message="Hello World!"
       ContentProps={{
        sx:{
          //Content styles goes here
        }
       }}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;ContentProps&lt;/em&gt;&lt;/strong&gt; is props that applied to SnackbarContent and &lt;strong&gt;&lt;em&gt;sx&lt;/em&gt;&lt;/strong&gt; is the "lets you work with a superset of CSS that packages all of the style functions exposed in @mui/system"&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's start with a simple style change:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Snackbar 
       open={open} 
       onClose={handleClose} 
       autoHideDuration={4000}
       message="Hello World!"
       ContentProps={{
        sx:{
          border: "1px solid black",
          borderRadius: "40px",
          color: "black",
          bgcolor: "lightgreen",
          fontWeight: "bold",
        }
       }}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, we add border, change colors and font weight.&lt;/p&gt;

&lt;p&gt;Our new Snackbar should look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0fx24mcr1caoc4380rkg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0fx24mcr1caoc4380rkg.png" alt=" " width="800" height="224"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It's sure better, but there is always things to improve&lt;/p&gt;

&lt;p&gt;Let's focus the text alignment, I really like centered texts in Snackbar. But adding &lt;code&gt;textAlign:"center"&lt;/code&gt; in sx props directly will not work, Why ?&lt;br&gt;
It's because we are only styling the SnackbarContent component. SnackbarContent also contains additional containers, such as the &lt;a href="https://mui.com/material-ui/api/snackbar-content/#css" rel="noopener noreferrer"&gt;message and action containers&lt;/a&gt;. To align the text properly, we need to override the styles of the message container in ContentProps, to make this happen we can use a syntax like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Snackbar 
       open={open} 
       onClose={handleClose} 
       autoHideDuration={4000}
       message="Hello World!"
       ContentProps={{
        sx:{
          border: "1px solid black",
          borderRadius: "40px",
          color: "black",
          bgcolor: "lightgreen",
          fontWeight: "bold",
          textAlign: "center",
          // centering our message
          width:"100%",
          "&amp;amp; .MuiSnackbarContent-message":{
            width:"inherit",
            textAlign: "center",
          }
        }
       }}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What are we doing here?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;First we add width prop to our SnackbarContent styles, which is &lt;code&gt;width:"100%"&lt;/code&gt;, We should add this because we want to fill all the spaces of Snackbar with SnckbarContent&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then we select the message wrapper: &lt;code&gt;"&amp;amp; .MuiSnackbarContent-message":{}&lt;/code&gt;, this is how we select elements in Material UI. The "&amp;amp;" symbol is used as a reference to the current component or container and  ".MuiSnackbarContent-message" portion of the selector targets the specific class name associated with the message element within the SnackbarContent component.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Next we add, &lt;code&gt;width:"inherit",textAlign: "center",&lt;/code&gt; inside of message container we select above.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally we have a centered Snackbar :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzewwrieo2girxbw50kzb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzewwrieo2girxbw50kzb.png" alt=" " width="800" height="234"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It is better right 😌&lt;/p&gt;

&lt;p&gt;You can add additional styles to further customize the SnackbarContent component according to your preferences.&lt;/p&gt;

&lt;p&gt;I suggest you to also add a &lt;a href="http://reactcommunity.org/react-transition-group/transition" rel="noopener noreferrer"&gt;Transition Property&lt;/a&gt; or change position of Snackbar easiliy with &lt;a href="https://mui.com/material-ui/react-snackbar/#positioned-snackbars" rel="noopener noreferrer"&gt;anchorOrigin&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://codesandbox.io/s/amazing-shirley-962ykp?file=/src/App.js" rel="noopener noreferrer"&gt;Code Sandbox link&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>ui</category>
      <category>css</category>
      <category>frontend</category>
    </item>
  </channel>
</rss>
