<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[SHSF Work - Medium]]></title>
        <description><![CDATA[Stay hungry, stay foolish. - Medium]]></description>
        <link>https://medium.com/shsfwork?source=rss----f3b24b29f0de---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>SHSF Work - Medium</title>
            <link>https://medium.com/shsfwork?source=rss----f3b24b29f0de---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:52:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/shsfwork" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Webpack, React & Redux, Styles Dependencies, and Deployment: A Step-by-Step Guide]]></title>
            <link>https://medium.com/shsfwork/webpack-react-redux-styles-dependencies-and-deployment-a-step-by-step-guide-ed82f4e3cf6f?source=rss----f3b24b29f0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/ed82f4e3cf6f</guid>
            <category><![CDATA[webpack-5]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Ozan Tekin]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 18:29:26 GMT</pubDate>
            <atom:updated>2025-04-21T18:29:12.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sa8NPffwsRl_TTMinQuxFw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Pawel Czerwinski</a> on <a href="https://unsplash.com/photos/purple-and-black-abstract-illustration-1QAXTrmx5rU?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4><strong>Introduction</strong></h4><p>In this article, I will be sharing my work on using Webpack with React. Let’s start with a brief overview of Webpack before moving on to the steps for adding dependencies, and deploying a Webpack project.</p><h4><strong>Content:</strong></h4><p><strong>What is Webpack? </strong><br><strong>How to Add Dependencies in Webpack? </strong><br><strong>How to Deploy a Webpack Project?</strong></p><h3>What is Webpack?</h3><p>Webpack is a module bundler that takes your code and its dependencies and creates static assets representing those modules. It allows you to write modular code and bundle it together into small packages to optimize load times. Webpack can be used with various languages and frameworks, including React.</p><h4>Installation</h4><ol><li>npm init -y: Creates a package.json file for your project.</li><li>npm i -D webpack webpack-cli: Installs Webpack and the Webpack Command Line Interface (CLI).</li><li>npm install webpack-dev-server --save-dev: Installs the Webpack development server.</li><li>npm i -D sass style-loader css-loader sass-loader: Installs tools for processing Sass and CSS files.</li><li>npm i -D html-webpack-plugin html-loader: Installs tools for processing HTML files.</li><li>npm i -D @babel/core babel-loader @babel/preset-env @babel/preset-react: Installs Babel tools. These tools make your JavaScript code compatible with older browsers.</li><li>npm i -D react react-dom: Installs the React library and the ReactDOM module.</li><li>npm i -D tailwindcss: Installs the Tailwind CSS library.</li><li>npm i -D postcss postcss-loader postcss-preset-env: Installs PostCSS tools.</li><li>npm i redux: Installs the Redux library.</li><li>npm install @reduxjs/toolkit: Installs the Redux Toolkit library.</li><li>npm i -D react-redux: Installs the React-Redux connection.</li><li>npm i --save-dev @redux-devtools/core: Installs Redux DevTools.</li><li>npm i -D react-router: Installs the React Router library.</li><li>npm i -D react-router-dom: Installs the React Router DOM module.</li><li>npm i -D webpack-bundle-analyzer: Installs the Webpack Bundle Analyzer tools. These tools visualize the sizes and usage of files in your project.</li></ol><p>To use these commands, navigate to your project directory and run them one by one. They will install the necessary tools and libraries for your React project.</p><h4>Files</h4><pre>touch webpack.config.js</pre><pre>touch .babelrc</pre><pre>// webpack.config.jsx<br>const path = require(&#39;path&#39;)<br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;)<br>const BundleAnalyzerPlugin =<br>  require(&#39;webpack-bundle-analyzer&#39;).BundleAnalyzerPlugin<br><br>module.exports = {<br>  mode: &#39;production&#39;,<br>  entry: path.resolve(__dirname, &#39;src/index.js&#39;),<br>  output: {<br>    path: path.resolve(__dirname, &#39;dist&#39;),<br>    filename: &#39;index.js&#39;,<br>    clean: true,<br>  },<br>  //devtool: &#39;source-map&#39;,<br>  devServer: {<br>    static: {<br>      directory: path.resolve(__dirname, &#39;dist&#39;),<br>    },<br>    port: 3000,<br>    open: true,<br>    hot: true,<br>    compress: true,<br>    historyApiFallback: true,<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.s[ac]ss$/i,<br>        use: [&#39;style-loader&#39;, &#39;css-loader&#39;, &#39;postcss-loader&#39;, &#39;sass-loader&#39;],<br>      },<br>      {<br>        test: /\.html$/,<br>        use: [<br>          {<br>            loader: &#39;html-loader&#39;,<br>          },<br>        ],<br>      },<br>      {<br>        test: /\.(js|jsx)$/,<br>        exclude: /node_modules/,<br>        use: {<br>          loader: &#39;babel-loader&#39;,<br>        },<br>      },<br>      {<br>        test: /\.(png|svg|jpg|jpeg|gif)$/i,<br>        type: &#39;asset/resource&#39;,<br>      },<br>    ],<br>  },<br>  plugins: [<br>    new HtmlWebpackPlugin({<br>      template: path.resolve(__dirname, &#39;public&#39;, &#39;index.html&#39;),<br>    }),<br>    //new BundleAnalyzerPlugin(),<br>  ],<br>  resolve: {<br>    extensions: [&#39;.js&#39;, &#39;.jsx&#39;, &#39;.md&#39;],<br>    modules: [path.resolve(__dirname, &#39;src&#39;), &#39;node_modules&#39;],<br>  },<br>}</pre><pre>touch .babelrc</pre><pre>// .babelrc<br>{<br>  &quot;presets&quot;: [<br>    &quot;@babel/preset-env&quot;,<br>    [<br>      &quot;@babel/preset-react&quot;,<br>      {<br>        &quot;runtime&quot;: &quot;automatic&quot;<br>      }<br>    ]<br>  ]<br>}</pre><pre>touch tailwind.config.js</pre><pre>// tailwind.config.js<br>module.exports = {<br>  content: [&#39;./public/index.html&#39;, &#39;./src/**/*.{html,js,jsx,ts,tsx}&#39;],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>}</pre><pre>touch postcss.config.js</pre><pre>// postcss.config.js<br>const tailwindcss = require(&#39;tailwindcss&#39;)<br>module.exports = {<br>  plugins: [&#39;postcss-preset-env&#39;, tailwindcss],<br>}</pre><pre>touch netlify.toml</pre><pre>// toml<br>[[redirects]]<br>  from = &quot;/*&quot;<br>  to = &quot;/&quot;<br>  status = 200</pre><pre>touch .gitignore</pre><pre>// .gitignore<br>node_modules</pre><pre>mkdir public</pre><pre>mkdir src</pre><pre>cd public/</pre><pre>touch index.html</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;base href=&quot;/&quot; /&gt;<br>    &lt;title&gt;Webpack - Starter&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><pre>cd ..</pre><pre>cd src</pre><pre>touch index.js</pre><pre>import &#39;./styles/main.scss&#39;<br>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import App from &#39;./App&#39;<br>import { BrowserRouter } from &#39;react-router-dom&#39;<br>import { Provider } from &#39;react-redux&#39;<br>import store from &#39;./redux/config/store.jsx&#39;<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;))<br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;BrowserRouter&gt;<br>      &lt;Provider store={store}&gt;<br>        &lt;App /&gt;<br>      &lt;/Provider&gt;<br>    &lt;/BrowserRouter&gt;<br>  &lt;/React.StrictMode&gt;<br>)</pre><pre>touch App.js</pre><pre>import Header from &#39;./components/Header/Header.jsx&#39;<br>import Navigation from &#39;./components/Navigation/Navigation.jsx&#39;<br>import { Route, Routes } from &#39;react-router-dom&#39;<br>import About from &#39;./routes/About/About.jsx&#39;<br>import Contact from &#39;./routes/Contact/Contact.jsx&#39;<br><br>export default function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Routes&gt;<br>        &lt;Route exact path=&#39;/&#39; element={&lt;Navigation /&gt;}&gt;<br>          &lt;Route index element={&lt;Header /&gt;} /&gt;<br>          &lt;Route path=&#39;about&#39; element={&lt;About /&gt;} /&gt;<br>          &lt;Route path=&#39;contact&#39; element={&lt;Contact /&gt;} /&gt;<br>        &lt;/Route&gt;<br>      &lt;/Routes&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>mkdir styles</pre><pre>mkdir routes</pre><pre>mkdir redux</pre><pre>mkdir components</pre><pre>cd styles</pre><pre>touch main.scss</pre><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><pre>cd ..</pre><pre>cd routes</pre><pre>mkdir About</pre><pre>cd About</pre><pre>touch About.jsx</pre><pre>export default function About() {<br>  return (<br>    &lt;div&gt;<br>      &lt;p className=&#39;text-red-600 text-2xl font-bold&#39;&gt; ABOUT PAGE! &lt;/p&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>cd ..</pre><pre>mkdir Contact</pre><pre>cd Contact</pre><pre>touch Contact.jsx</pre><pre>import &#39;./contact.styles.scss&#39;<br>export default function Contact() {<br>  return (<br>    &lt;div className=&#39;contact&#39;&gt;<br>      &lt;header className=&#39;contact-header&#39;&gt;<br>        &lt;h1&gt; Contact Page &lt;/h1&gt;<br>      &lt;/header&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>touch contact.styles.scss</pre><pre>.contact {<br>  background-color: cadetblue;<br>  .contact-header {<br>    padding: 10px;<br>    h1 {<br>      color: brown;<br>      font-weight: bold;<br>    }<br>  }<br>}</pre><pre>cd ..</pre><pre>cd ..</pre><pre>cd redux</pre><pre>mkdir actions</pre><pre>mkdir config</pre><pre>cd config</pre><pre>touch store.jsx</pre><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;</pre><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;</pre><pre>const store = configureStore({<br>  reducer: {},<br>})<br>export default store</pre><pre>cd ..</pre><pre>cd ..</pre><pre>cd components/</pre><pre>mkdir Navigation</pre><pre>mkdir Header</pre><pre>cd Navigation</pre><pre>touch Navigation.jsx</pre><pre>import { NavLink, Outlet } from &#39;react-router-dom&#39;</pre><pre>export default function Navigation() {<br>  return (<br>    &lt;nav&gt;<br>      &lt;ul className=&#39;flex gap-8&#39;&gt;<br>        &lt;li&gt;<br>          &lt;NavLink to=&#39;/&#39;&gt; Home &lt;/NavLink&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;NavLink to=&#39;/about&#39;&gt; About &lt;/NavLink&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;NavLink to=&#39;contact&#39;&gt; Contact &lt;/NavLink&gt;<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>      &lt;Outlet /&gt;<br>    &lt;/nav&gt;<br>  )<br>}</pre><pre>cd ..</pre><pre>cd Header</pre><pre>touch Header.jsx</pre><pre>export default function Header() {<br>  return (<br>    &lt;header&gt;<br>      &lt;h1 className=&#39;font-bold text-3xl text-blue-600&#39;&gt; Webpack Starter &lt;/h1&gt;<br>    &lt;/header&gt;<br>  )<br>}</pre><pre>package.json - scripts</pre><pre>&quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;webpack serve --mode development&quot;,<br>    &quot;start&quot;: &quot;webpack serve --mode development&quot;,<br>    &quot;build&quot;: &quot;webpack --mode development&quot;<br>  },</pre><pre>&lt;!--index.html --&gt;<br><br>&lt;base href=&quot;/&quot; /&gt;</pre><h4>Usage</h4><ul><li>Run Dev Server (Port 3000): npm run dev</li><li>Build for production: npm run build</li></ul><h4>Folder and File structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*HTNDC4X2JBNL8xjSPkA3WQ.png" /></figure><h4>Conclusion</h4><p>In this article, we discussed using Webpack with React and the steps for adding dependencies and deploying a Webpack project.</p><p><a href="https://starter-kit-webpack.netlify.app/"><strong><em>Live Demo</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*ct9ay6U2yxl892o_MYe_dQ.png" /></figure><ul><li><a href="https://github.com/ozantekin/webpack-starter">GitHub - ozantekin/webpack-starter: Here is a detailed starter kit for getting started with Webpack. If you follow these steps carefully, you will complete the installation.</a></li><li><a href="https://medium.com/shsfwork">SHSF Work</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed82f4e3cf6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shsfwork/webpack-react-redux-styles-dependencies-and-deployment-a-step-by-step-guide-ed82f4e3cf6f">Webpack, React &amp; Redux, Styles Dependencies, and Deployment: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/shsfwork">SHSF Work</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flex Your CSS Muscles: Understanding and Using the flex:1 Property]]></title>
            <link>https://medium.com/shsfwork/flex-your-css-muscles-understanding-and-using-the-flex-1-property-6657fb2382b3?source=rss----f3b24b29f0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/6657fb2382b3</guid>
            <category><![CDATA[css-flex]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Ozan Tekin]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 18:28:15 GMT</pubDate>
            <atom:updated>2026-02-10T07:50:37.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pf8lNQTTcwXOU3D9bBImnQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Pawel Czerwinski</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-black-and-brown-surface-YFlbfrxm4TM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Hi! In this write-up, you can access the summary article I’ve prepared on flex:1.</p><h4>Content:</h4><p><strong>What does flex 1 mean?</strong></p><p>The <strong>flex:1</strong> property is a shorthand for the <strong>flex-grow</strong> property, one of the many properties that can be used to control the layout of elements within a flex container. The <strong>flex-grow</strong> property specifies how much of the available space within a container an element should take up, relative to the other elements.</p><p>When the value of <strong>flex-grow</strong> is set to <strong>1</strong>, it means that the element will take up as much space as possible, while still allowing other elements to take up their share of the area. For example, if a container has three child elements, all with a <strong>flex-grow</strong> value of <strong>1</strong>, each element will take up an equal amount of the available space.</p><p>It is also possible to set different values for <strong>flex-grow</strong> for different elements, in order to control how much space each element takes up. For example, if an element has a <strong>flex-grow</strong> value of <strong>2</strong>, it will take up twice as much space as an element with a <strong>flex-grow</strong> value of <strong>1</strong>.</p><p>In addition to <strong>flex-grow</strong>, there are other properties that can be used to control the layout of elements within a flex container, such as <strong>flex-shrink</strong> and <strong>flex-basis</strong>. The <strong>flex-shrink</strong> property controls how much an element will shrink when the container is too small, and the <strong>flex-basis</strong> property controls the initial size of an element before any remaining space is distributed.</p><p>When flex:1 is used, it is shorthand for <strong>flex-grow:1 | flex-shrink:1 | flex-basis:0%</strong>. This shorthand is used to set all three properties in one line of code quickly.</p><p>In summary, the <strong>flex:1</strong> property in CSS is a shorthand for the <strong>flex-grow</strong> property, which specifies how much of the available space within a container an element should take up, relative to the other elements. It is used to control the layout of elements within a flex container and allows for a more efficient and flexible way to distribute space among elements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6657fb2382b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shsfwork/flex-your-css-muscles-understanding-and-using-the-flex-1-property-6657fb2382b3">Flex Your CSS Muscles: Understanding and Using the flex:1 Property</a> was originally published in <a href="https://medium.com/shsfwork">SHSF Work</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async Operations in Redux with the Redux Toolkit Thunk]]></title>
            <link>https://medium.com/shsfwork/async-operations-in-redux-with-the-redux-toolkit-thunk-e7d024cbf875?source=rss----f3b24b29f0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/e7d024cbf875</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Ozan Tekin]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 18:02:38 GMT</pubDate>
            <atom:updated>2026-02-10T07:51:20.092Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this writing, I have compiled my work on Thunk. Happy reading!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hKgavneADU2FUCNVDi5jQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Pawel Czerwinski</a> on <a href="https://unsplash.com/photos/water-splash-in-close-up-photography-5x7kyu3J4Xs?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Content:</h4><p>What is the redux-toolkit thunk?</p><h4>Introduction</h4><p>Let’s try to see the big picture by initially making brief explanations about “<strong>redux-toolkit</strong>” and “<strong>thunk</strong>”.</p><p><strong>Redux-toolkit: </strong>You can think of it as an extension of the Redux library and is used to simplify data management in an application. Redux-toolkit supports async operations called “thunk”.</p><p><strong>Thunk:</strong> It is a function that delays the execution of a function or block of code until it is called again. In Redux, it is used to manage async operations (e.g. fetching data or database operations). With this extension, managing async operations become easier and your application can become more flexible.</p><h4>Conclusion</h4><p>The Redux Toolkit Thunk is a <strong>middleware</strong> for the Redux library that allows you to write async logic that interacts with the store. It is designed to make it easier to work with <strong>asynchronous actions</strong> in Redux, and it enables you to write action creators that return a function instead of an action object. This function called a “thunk” can be used to perform async logic, such as making an <strong>API request </strong>or <strong>dispatching multiple actions</strong>. The thunk can also be used to perform <strong>conditional logic</strong>, such as dispatching a <strong>different action depending on the result of the async operation</strong>. Overall, the Redux Toolkit Thunk is a powerful tool for managing async behavior in a Redux application.</p><h4>Practical Example Project</h4><pre>// index.js<br><br>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import &#39;./index.css&#39;<br>import App from &#39;./App&#39;<br><br>import { store } from &#39;./redux/config/store&#39;<br>import { Provider } from &#39;react-redux&#39;<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;))<br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Provider store={store}&gt;<br>      &lt;App /&gt;<br>    &lt;/Provider&gt;<br>  &lt;/React.StrictMode&gt;<br>)</pre><pre>// store.js<br><br>import { configureStore } from &#39;@reduxjs/toolkit&#39;<br>import contentSlice from &#39;../slice/contentSlice&#39;<br><br>export const store = configureStore({<br>  reducer: {<br>    content: contentSlice,<br>  },<br>})</pre><pre>// contentSlice.js<br><br>import { createAsyncThunk, createSlice } from &#39;@reduxjs/toolkit&#39;<br>import axios from &#39;axios&#39;<br><br>const initialState = {<br>  contents: [],<br>  isLoading: false,<br>  error: null,<br>}<br><br>export const fetchContent = createAsyncThunk(<br>  &#39;content/fetchContent&#39;,<br>  async () =&gt; {<br>    const res = await axios(&#39;https://jsonplaceholder.typicode.com/photos&#39;)<br>    const data = await res.data<br>    return data<br>  }<br>)<br><br>export const contentSlice = createSlice({<br>  name: &#39;content&#39;,<br>  initialState,<br>  reducers: {},<br>  extraReducers: (builder) =&gt; {<br>    builder.addCase(fetchContent.pending, (state) =&gt; {<br>      state.isLoading = true<br>    })<br>    builder.addCase(fetchContent.fulfilled, (state, action) =&gt; {<br>      state.isLoading = false<br>      state.contents = action.payload<br>    })<br>    builder.addCase(fetchContent.rejected, (state, action) =&gt; {<br>      state.isLoading = false<br>      state.error = action.error.message<br>    })<br>  },<br>})<br><br>export default contentSlice.reducer</pre><pre>// App.js<br><br>function App() {<br>  const dispatch = useDispatch()<br><br>  useEffect(() =&gt; {<br>    dispatch(fetchContent())<br>  }, [dispatch])<br><br>  const contents = useSelector((state) =&gt; state.content.contents)<br>  const isLoading = useSelector((state) =&gt; state.content.isLoading)<br>  const error = useSelector((state) =&gt; state.content.error)<br><br>  if (isLoading) {<br>    return &#39;loading...&#39;<br>  }<br><br>  if (error) {<br>    return error<br>  }<br><br>  return (<br>    &lt;div className=&#39;grid gap-4 grid-cols-2  md:grid-cols-4 lg:grid-cols-8  p-4&#39;&gt;<br>      {contents.map((content) =&gt; (<br>        &lt;div key={content.id}&gt;<br>          &lt;img<br>            src={`${content.thumbnailUrl}`}<br>            alt={`${content.title}`}<br>            className=&#39;w-full h-full rounded&#39;<br>          /&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default App</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7d024cbf875" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shsfwork/async-operations-in-redux-with-the-redux-toolkit-thunk-e7d024cbf875">Async Operations in Redux with the Redux Toolkit Thunk</a> was originally published in <a href="https://medium.com/shsfwork">SHSF Work</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Raindrop API with Next.js to Build a Bookmark Page]]></title>
            <link>https://medium.com/shsfwork/using-raindrop-api-with-next-js-to-build-a-bookmark-page-392f527e1b3e?source=rss----f3b24b29f0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/392f527e1b3e</guid>
            <category><![CDATA[raindrop]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[app-router]]></category>
            <dc:creator><![CDATA[Ozan Tekin]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 17:50:45 GMT</pubDate>
            <atom:updated>2025-04-22T21:20:54.254Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Step-by-Step Guide to Integrating Raindrop Collections and Bookmarks into Your Next.js Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgWbBAFwA8kMRCuaEUss_g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Pawel Czerwinski</a> on <a href="https://unsplash.com/photos/black-grey-and-blue-painting-1JLIC7bnoZA?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Headings</h4><ul><li>How to Generate a Raindrop Access Token?</li><li>How to Create Collections?</li><li>How to Write a GET Service for Collections?</li><li>How to Write a GET Service for Bookmarks?</li><li>How to Integrate Services into the UI?</li></ul><h3>1. How to Generate a Raindrop Access Token</h3><p>First, create a Raindrop account if you don’t have one.</p><p>Navigate to the settings by clicking on your user information in the upper-right corner. Go to the “Integrations” section. Under the “For developers” area, create a new app and generate a test token.</p><p>This token will be used shortly in our environment configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNvowapWfPyKytCSbIH9MQ.png" /></figure><h3>2. How to Create Collections</h3><p>On the main page, use the plus button next to the collections menu to quickly create a new collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*ELstnzCvsayiYJMyumyeLQ.png" /></figure><h3>3. How to Write a GET Service for Collections</h3><p>Add your access token to your environment variables file. Create a .env file at the root of your project and add:</p><pre>NEXT_PUBLIC_RAINDROP_ACCESS_TOKEN=[your access token]</pre><p>Next, create a lib directory and add a raindrop.tsx file:</p><pre>import &quot;server-only&quot;;<br>import { cache } from &quot;react&quot;;<br><br>const options = {<br>  method: &quot;GET&quot;,<br>  headers: {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    Authorization: `Bearer ${process.env.NEXT_PUBLIC_RAINDROP_ACCESS_TOKEN}`,<br>  },<br>};<br><br>const RAINDROP_API_URL = &quot;https://api.raindrop.io/rest/v1&quot;;</pre><pre>export const getCollections = cache(async () =&gt; {<br>  try {<br>    const response = await fetch(`${RAINDROP_API_URL}/collections`, options);<br>    const collections = await response.json();<br>    return collections;<br>  } catch (error) {<br>    console.info(error);<br>    return null;<br>  }<br>});</pre><p>This function fetches your collections without their bookmarks.</p><h3>4. How to Write a GET Service for Bookmarks</h3><p>To fetch bookmarks within a collection, extend the raindrop.tsx file:</p><pre>export const getBookmark = cache(async (id: number, pageIndex = &quot;0&quot;) =&gt; {<br>  try {<br>    const response = await fetch(<br>      `${RAINDROP_API_URL}/raindrops/${id}?` +<br>        new URLSearchParams({<br>          page: pageIndex,<br>          perpage: &quot;100&quot;,<br>        }),<br>      options<br>    );<br>    return await response.json();<br>  } catch (error) {<br>    console.info(error);<br>    return null;<br>  }<br>});</pre><p>This function retrieves bookmarks for a specific collection.</p><h3>5. How to Integrate Services into the UI</h3><p>Create the main page component under the pages directory:</p><pre>import { getBookmark, getCollections } from &quot;@ozantekin/libs/raindrop&quot;;<br>import MainPage from &quot;@ozantekin/modules/MainPage&quot;;<br><br>export const dynamic = &quot;force-dynamic&quot;;<br><br>async function Home() {<br>  const [bookmark, collections] = await Promise.all([<br>    getBookmark(0),<br>    getCollections(),<br>  ]);<br>  return &lt;MainPage bookmark={bookmark} collections={collections} /&gt;;<br>}<br><br>export default Home;</pre><p>Next, create the MainPage component under the modules directory:</p><pre>&quot;use client&quot;;<br><br>import Link from &quot;next/link&quot;;<br><br>interface MainPageProps {<br>  bookmark: BookmarkProps;<br>  collections: CollectionsProps;<br>}<br><br>function MainPage({ bookmark, collections }: MainPageProps) {<br>  return (<br>    &lt;main className=&quot;grid grid-cols-4 gap-4 p-4&quot;&gt;<br>      {bookmark.items.map((item: any) =&gt; {<br>        return (<br>          &lt;div<br>            key={item.id}<br>            className=&quot;max-w-sm bg-white border border-gray-200 rounded-lg shadow &quot;<br>          &gt;<br>            &lt;img className=&quot;rounded-t-lg&quot; src={item.cover} alt={item.title} /&gt;<br><br>            &lt;div className=&quot;p-5 space-y-2&quot;&gt;<br>              &lt;h5 className=&quot;mb-2 text-2xl font-bold tracking-tight text-gray-900 &quot;&gt;<br>                {item.title}<br>              &lt;/h5&gt;<br><br>              &lt;p className=&quot;mb-3 font-normal text-gray-700 &quot;&gt;{item.excerpt}&lt;/p&gt;<br>              &lt;p className=&quot;text-xs text-gray-400&quot;&gt; {item.domain} &lt;/p&gt;<br>              &lt;Link<br>                href={item.link}<br>                target=&quot;_blank&quot;<br>                className=&quot;inline-flex items-center px-3 py-2 text-sm font-medium text-center text-white bg-orange-500 rounded-lg hover:bg-orange-600 focus:ring-4 focus:outline-none focus:ring-orange-300 &quot;<br>              &gt;<br>                Go to bookmark<br>                &lt;svg<br>                  className=&quot;rtl:rotate-180 w-3.5 h-3.5 ms-2&quot;<br>                  aria-hidden=&quot;true&quot;<br>                  xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>                  fill=&quot;none&quot;<br>                  viewBox=&quot;0 0 14 10&quot;<br>                &gt;<br>                  &lt;path<br>                    stroke=&quot;currentColor&quot;<br>                    stroke-linecap=&quot;round&quot;<br>                    stroke-linejoin=&quot;round&quot;<br>                    stroke-width=&quot;2&quot;<br>                    d=&quot;M1 5h12m0 0L9 1m4 4L9 9&quot;<br>                  /&gt;<br>                &lt;/svg&gt;<br>              &lt;/Link&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        );<br>      })}<br>    &lt;/main&gt;<br>  );<br>}<br><br>export default MainPage;</pre><h4>Final Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzvyB3ccpJS83QmZpEho9A.png" /></figure><p>By following these steps, you will have a functional bookmark page integrated with the Raindrop API and Next.js. This setup fetches and displays your collections and their bookmarks efficiently.</p><p><em>Don’t miss out on these kinds of articles by following or subscribing to the newsletter. Your comments and likes motivate me.</em></p><ul><li><a href="https://github.com/SHSFWork/raindrop-nextjs-bookmark-starter-kit">GitHub - SHSFWork/raindrop-nextjs-bookmark-starter-kit: A sleek, modern bookmark manager powered by Raindrop.io API and built with Next.js 15 (App Router), TypeScript, Tailwind CSS, and ShadCN UI components.</a></li><li><a href="https://medium.com/shsfwork">SHSF Work</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=392f527e1b3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shsfwork/using-raindrop-api-with-next-js-to-build-a-bookmark-page-392f527e1b3e">Using Raindrop API with Next.js to Build a Bookmark Page</a> was originally published in <a href="https://medium.com/shsfwork">SHSF Work</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Notion API? [Waitlist]]]></title>
            <link>https://medium.com/shsfwork/how-to-use-notion-api-waitlist-section-1-31238d16f46b?source=rss----f3b24b29f0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/31238d16f46b</guid>
            <category><![CDATA[notion-api]]></category>
            <category><![CDATA[api-route]]></category>
            <category><![CDATA[app-router]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ozan Tekin]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 17:50:30 GMT</pubDate>
            <atom:updated>2025-04-22T21:22:00.062Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How to create a waitlist using Next.js App Router, API routes, and Notion API?</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibsgaU1YKA_9pToID6NE2A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Pawel Czerwinski</a> on <a href="https://unsplash.com/photos/blue-and-black-abstract-painting-prMn9KINLtI?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Headings</h4><ul><li>How to create a database in Notion?</li><li>How to create Notion integration and secret authentication?</li><li>How to connect integration with the database?</li><li>How to add an internal integration secret and Database ID?</li><li>What is Notionhq Client Package?</li><li>How to perform a Notion API post-operation with Next.js App Router?</li><li>How to write a POST service within API Route?</li><li>How to send a request to the POST service?</li></ul><h3>How to Create a Database in Notion?</h3><p>Add a page and then create a table within the page.</p><p>You’re free to manage the fields within the table as you wish. In this write-up, I’ll focus on ID, email, and created time fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*9QqoCABO5ymBCfoKX_2g9g.png" /></figure><h3>How to Create Notion Integration and Secret Authentication?</h3><p>You can click <a href="https://developers.notion.com/">here</a> for Notion API documentation and integration.</p><p>Go to your integrations page, sign in to your Notion account, and then create a new integration.</p><p>You can add a name and logo for your integration. I’ll use a sample integration for this write-up.</p><p>After this step, you’ll be presented with an internal integration secret. We’ll add this key to the env file of our project.</p><h3>How to Connect Integration with the Database?</h3><p>Go back to the waitlist table you created in Notion. From the menu that appears on the top left, select the integration you created through “connect to.” That’s all there is to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ogh7lTYDd3YkeXEXZdw_xQ.png" /></figure><h3>How to Add Internal Integration Secret and Database ID?</h3><p>While creating the integration, give the key a name as you wish and add it to the env file. (E.g., <strong>NOTION_SECRET_AUTH</strong>) This key will be used in the Notion client.</p><p>Go to the waitlist database where you linked the integration. Click on “share” in the top left corner and click “copy link.” It will give you a link like the one below, and you just need to get the DATABASE_ID.</p><p><a href="https://www.notion.so/[notion_name]/[DATABASE_ID]?v=[numbers]&amp;pvs=[numbers]"><strong>https://www.notion.so/[notion_name]/[DATABASE_ID]?v=[numbers]&amp;pvs=[numbers]</strong></a></p><p>You can add it to the .env file like this: <strong>NOTION_WAITLIST_DATABASE_ID</strong></p><h3>What is Notionhq Client Package?</h3><p>The <a href="https://www.npmjs.com/package/@notionhq/client">@notionhq/client</a> package is a simple and easy-to-use client for the Notion API. I’ll use this package since it’s recommended in the documentation.</p><h3>How do you perform a Notion API Post Operation with Next.js App Router?</h3><p>Create a folder named API under the app folder.</p><p>To maintain consistency, I’ll use the following folder structure in subsequent sections:</p><p>— app<br> — — API<br> —— — notion<br> — — — — waitlist<br> —— — — — route.ts</p><p>In the route.ts file, write a post service using the @notionhq/client package.</p><h3>How to Write a POST Service within an API Route?</h3><p>We’ll use the <strong>NOTION_SECRET_AUTH</strong> and <strong>NOTION_WAITLIST_DATABASE_ID</strong> we added to .env.production with the @notionhq/client package.</p><pre>import { Client } from &quot;@notionhq/client&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br><br>export async function POST(request: Request) {<br>  const body = await request.json();<br>  try {<br>    const notion = new Client({ auth: process.env.NOTION_SECRET_AUTH });<br>    const response = await notion.pages.create({<br>      parent: {<br>        database_id: process.env.NOTION_WAITLIST_DATABASE_ID,<br>      },<br>      properties: {<br>        Email: {<br>          title: [<br>            {<br>              text: {<br>                content: body?.email,<br>              },<br>            },<br>          ],<br>        },<br>      },<br>    });<br>    return NextResponse.json(<br>      { success: true},<br>      { status: 200 }<br>    );<br>  } catch (error) {<br>    return NextResponse.json({ success: false }, { status: 500 });<br>  }<br>}</pre><p>Email is a field we added to our table. Since it’s a title and rich text, this is the basic usage. For more detailed database properties, <a href="https://developers.notion.com/reference/database#all-databases">refer to</a>.</p><h3>How to Send a Request to the POST Service?</h3><p>Since this series of articles is the first part of a whole, I’ll use Axios.</p><pre>const onSubmit = async (data: z.infer&lt;typeof FormSchema&gt;) =&gt; {<br>  try {<br>    await axios.post(&quot;/api/notion/waitlist&quot;, {<br>      email: data.email,<br>    });<br><br>    form.reset();<br>    toast({<br>      title: &quot;Welcome 🎊&quot;,<br>      description: &quot;toast msg&quot;,<br>    });<br>  } catch (error) {<br>    toast({<br>      variant: &quot;destructive&quot;,<br>      title: &quot;Oops! Something went wrong&quot;,<br>      description: &quot;Please try again later.&quot;,<br>    });<br>  }<br>};</pre><p>Note: We’re sending the request based on the folder structure we created under App: <strong>/api/notion/waitlist</strong></p><p>In addition to the request, toast and form components are used. You only need to focus on the Axios operation.</p><p>With this process, a row with ID, email, and created time will be added to your database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Brtga5hY9G6b96QV8Hd-Jg.png" /></figure><p>This write-up shows how to use the NOTION API and API usage within Next.js APP Router. This is just a small part of a large whole. In future articles, we’ll focus on adding new items to the database and fetching what we’ve added (server-side). See you in the next section, “Join Us.” 👋</p><p><em>Don’t miss out on these kinds of articles by following or subscribing to the newsletter. Your comments and likes motivate me.</em></p><ul><li><a href="https://github.com/SHSFWork/notion-nextjs-waitlist-starter-kit">GitHub - SHSFWork/notion-nextjs-waitlist-starter-kit: This is a modern waitlist application built with Next.js App Router, TypeScript, Tailwind CSS, and ShadCN UI. It seamlessly integrates with the Notion API to store waitlist signups in a Notion database.</a></li><li><a href="https://medium.com/shsfwork">SHSF Work</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31238d16f46b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shsfwork/how-to-use-notion-api-waitlist-section-1-31238d16f46b">How to Use Notion API? [Waitlist]</a> was originally published in <a href="https://medium.com/shsfwork">SHSF Work</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add a Copy to Clipboard Button in MDX with Next.js]]></title>
            <link>https://medium.com/shsfwork/how-to-add-a-copy-to-clipboard-button-in-mdx-with-next-js-e1a182f40690?source=rss----f3b24b29f0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/e1a182f40690</guid>
            <category><![CDATA[mdx]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[rehype-pretty-code]]></category>
            <category><![CDATA[copy-to-clipboard]]></category>
            <category><![CDATA[contentlayer]]></category>
            <dc:creator><![CDATA[Ozan Tekin]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 17:49:52 GMT</pubDate>
            <atom:updated>2025-04-22T23:42:56.975Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Add a Copy to Clipboard Button in MDX with Next.js?</h3><h4>In this article, you&#39;ll learn how to easily create a copy to clipboard button using Rehype Pretty Code. We are developing a blog site with Contentlayer #1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zr-zl0zaom9b5PxxmD_zTA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Pawel Czerwinski</a> on <a href="https://unsplash.com/photos/green-and-pink-abstract-art-z7prq6BtPE4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Table of Contents</h4><ul><li>Before You Start</li><li>Introduction</li><li>Setting Up the Rehype Pretty Code Plugin</li><li>Pre Component</li><li>Code Component</li><li>Rendering MDX Content</li><li>Copy Button</li><li>Adding CopyButton to Pre Component</li><li>Conclusion</li></ul><h3>Before You Start</h3><p>By the end of this series, you’ll have a blog page with dark-light theme, SEO optimization, and enhancements to improve the reading experience. The <a href="https://github.com/ozantekin/nextjs-blog-template"><strong><em>nextjs-blog-template</em></strong></a> repository, linked at the end of this article, is a step ahead in this series and provides answers to your UI/UX questions. Check out the repository to get a head start and quickly customize your blog.</p><blockquote><strong><em>Note:</em></strong><em> Before starting, follow the simple steps in the Contentlayer documentation to complete the basic setup. For the relevant setup, refer to </em><a href="https://contentlayer.dev/docs/getting-started-cddd76b7"><em>Contentlayer Documentation</em></a><em>.</em></blockquote><h3>Introduction</h3><p>Follow these steps to add a “copy to clipboard” button to the code blocks in your Next.js application created with MDX. This feature enhances the user experience and makes code sharing easier.</p><pre>npm install rehype-pretty-code shiki unist-util-visit</pre><p>Now, let’s move on to the steps we’ll follow.</p><h3>Setting Up the Rehype Pretty Code Plugin</h3><p>Add this section to the makeSource function in your contentlayer.config.ts file.</p><pre>  mdx: {<br>    rehypePlugins: [<br>      () =&gt; (tree) =&gt; {<br>        visit(tree, (node) =&gt; {<br>          if (node?.type === &quot;element&quot; &amp;&amp; node?.tagName === &quot;pre&quot;) {<br>            const [codeEl] = node.children;<br><br>            if (codeEl.tagName !== &quot;code&quot;) return;<br><br>            node.__rawString__ = codeEl.children?.[0].value;<br>          }<br>        });<br>      },<br>      [<br>        // @ts-ignore<br>        rehypePrettyCode,<br>        {<br>          theme: &quot;github-dark&quot;,<br>          keepBackground: false,<br>          onVisitLine(node: any) {<br>            if (node.children.length === 0) {<br>              node.children = [{ type: &quot;text&quot;, value: &quot; &quot; }];<br>            }<br>          },<br>        },<br>      ],<br>      () =&gt; (tree) =&gt; {<br>        visit(tree, (node) =&gt; {<br>          if (node?.type === &quot;element&quot; &amp;&amp; node?.tagName === &quot;figure&quot;) {<br>            if (!(&quot;data-rehype-pretty-code-figure&quot; in node.properties)) {<br>              return;<br>            }<br><br>            const preElement = node.children.at(-1);<br>            if (preElement.tagName !== &quot;pre&quot;) {<br>              return;<br>            }<br><br>            preElement.properties[&quot;__rawString__&quot;] = node.__rawString__;<br>          }<br>        });<br>      },<br>    ],<br>  },</pre><h3>Pre Component</h3><pre>interface PreProps extends React.HTMLProps&lt;HTMLPreElement&gt; {<br>  __rawString__?: string;<br>  [&quot;data-language&quot;]?: string;<br>}<br><br>export function PreCustom(props: PreProps) {<br>  const {<br>    children,<br>    __rawString__ = &quot;&quot;,<br>    [&quot;data-language&quot;]: dataLanguage = &quot;Shell&quot;,<br>  } = props;<br><br>  return (<br>    &lt;pre<br>      className=&quot;rounded-xl bg-slate-950  relative overflow-hidden p-[0.5rem] shadow-smooth&quot;<br>      {...props}<br>    &gt;<br>      &lt;p className=&quot;absolute bottom-0 right-0 capitalize text-xs font-medium bg-slate-700 text-white p-1 rounded-tl-lg&quot;&gt;<br>        {dataLanguage}<br>      &lt;/p&gt;<br>      {children}<br>    &lt;/pre&gt;<br>  );<br>}</pre><h3>Code Component</h3><pre>import { HTMLAttributes } from &quot;react&quot;;<br>import { cn } from &quot;@/utils/cn&quot;;<br><br>export const BasicItems = {<br>  code: (props: HTMLAttributes&lt;HTMLElement&gt;) =&gt; {<br>    const { className, ...rest } = props;<br>    return (<br>      &lt;code<br>        className={cn(<br>          &quot;rounded-sm bg-slate-950 px-[0.5rem] py-1 font-mono text-sm text-foreground text-pretty leading-relaxed text-white&quot;,<br>          className<br>        )}<br>        {...rest}<br>      /&gt;<br>    );<br>  },<br>};</pre><h3>Rendering MDX Content</h3><pre>import { BasicItems } from &quot;./basic-items&quot;;<br>import { PreCustom } from &quot;./pre-component&quot;;<br><br>export const MDXComponents = {<br>  pre: PreCustom,<br>  ...BasicItems,<br>};</pre><pre>&quot;use client&quot;;<br><br>import { useMDXComponent } from &quot;next-contentlayer/hooks&quot;;<br>import { MDXComponents } from &quot;@/components/mdx/components&quot;;<br><br>interface MdxProps {<br>  code: string;<br>}<br><br>export function Mdx(props: MdxProps) {<br>  const { code } = props;<br>  const Component = useMDXComponent(code);<br><br>  return &lt;Component components={MDXComponents} /&gt;;<br>}</pre><h3>Copy Button</h3><pre>&quot;use client&quot;;<br><br>import { Button, ButtonProps } from &quot;@/components/shadcn/button&quot;;<br>import { cn } from &quot;@/utils/cn&quot;;<br>import { Checks, ClipboardText } from &quot;@phosphor-icons/react&quot;;<br>import { useState } from &quot;react&quot;;<br><br>interface CopyButtonProps extends ButtonProps {<br>  text: string;<br>  className?: string;<br>}<br><br>export function CopyButton({ text, className, ...props }: CopyButtonProps) {<br>  const [isCopied, setIsCopied] = useState(false);<br><br>  const copy = async () =&gt; {<br>    await navigator.clipboard.writeText(text);<br>    setIsCopied(true);<br><br>    setTimeout(() =&gt; {<br>      setIsCopied(false);<br>    }, 700);<br>  };<br><br>  return (<br>    &lt;Button<br>      size=&quot;icon&quot;<br>      className={cn(&quot;size-7 !bg-slate-700 !text-white&quot;, className)}<br>      disabled={isCopied}<br>      onClick={copy}<br>      aria-label=&quot;Copy&quot;<br>      {...props}<br>    &gt;<br>      &lt;span className=&quot;sr-only&quot;&gt;Copy&lt;/span&gt;<br>      {isCopied ? &lt;Checks className=&quot;text-green-400&quot; /&gt; : &lt;ClipboardText /&gt;}<br>    &lt;/Button&gt;<br>  );<br>}</pre><h3>Adding CopyButton to Pre Component</h3><pre>import { CopyButton } from &quot;./copy-button&quot;;<br><br>interface PreProps extends React.HTMLProps&lt;HTMLPreElement&gt; {<br>  __rawString__?: string;<br>  [&quot;data-language&quot;]?: string;<br>}<br><br>export function PreCustom(props: PreProps) {<br>  const {<br>    children,<br>    __rawString__ = &quot;&quot;,<br>    [&quot;data-language&quot;]: dataLanguage = &quot;Shell&quot;,<br>  } = props;<br><br>  return (<br>    &lt;pre<br>      className=&quot;rounded-xl bg-slate-950  relative overflow-hidden p-[0.5rem] shadow-smooth&quot;<br>      {...props}<br>    &gt;<br>      &lt;p className=&quot;absolute bottom-0 right-0 capitalize text-xs font-medium bg-slate-700 text-white p-1 rounded-tl-lg&quot;&gt;<br>        {dataLanguage}<br>      &lt;/p&gt;<br>      &lt;CopyButton<br>        text={__rawString__}<br>        className=&quot;absolute right-1 top-1 shadow-smooth&quot;<br>      /&gt;<br><br>      {children}<br>    &lt;/pre&gt;<br>  );<br>}</pre><h3>Conclusion</h3><p>By following these steps, you can easily add a “copy to clipboard” button to your MDX-based site created with Next.js and Contentlayer. This feature will significantly improve code sharing and user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exNv5Yrzd1MY2cjkFBNGzA.png" /></figure><p>Feel free to explore the nextjs-blog-template repository for further customization and enhancements to your blog. If you have any questions or need further assistance, please leave a comment below or reach out to us on our GitHub repository. 👋</p><ul><li><a href="https://github.com/ozantekin/nextjs-blog-template">GitHub - ozantekin/nextjs-blog-template: Blog template built with Next.js, Tailwind CSS, Shadcn, and Contentlayer. Includes dark-light theme support and easy customization.</a></li><li><a href="https://medium.com/shsfwork">SHSF Work</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a182f40690" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shsfwork/how-to-add-a-copy-to-clipboard-button-in-mdx-with-next-js-e1a182f40690">How to Add a Copy to Clipboard Button in MDX with Next.js</a> was originally published in <a href="https://medium.com/shsfwork">SHSF Work</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing a Next.js Form Component with Playwright]]></title>
            <link>https://medium.com/shsfwork/testing-a-next-js-form-component-with-playwright-89fea1af78a4?source=rss----f3b24b29f0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/89fea1af78a4</guid>
            <category><![CDATA[automated-ui-testing]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend-testing]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[playwright-test]]></category>
            <dc:creator><![CDATA[Ozan Tekin]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 17:48:29 GMT</pubDate>
            <atom:updated>2025-04-21T18:17:30.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xnt4_xnkeK92fTJ4n6X62A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@solenfeyissa?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Solen Feyissa</a> on <a href="https://unsplash.com/photos/red-and-white-abstract-painting-sqim3_0-siM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Table of Contents</h3><ol><li>Introduction</li><li>Form Component Explanation</li><li>Understanding data-testid Usage in Tests</li><li>Test Code Explanation</li><li>Playwright Setup and Execution</li><li>Conclusion</li></ol><h3>Introduction</h3><p>Testing user interactions in modern web applications is a crucial part of ensuring quality and user satisfaction. In this article, we will break down a Form component created in a Next.js project and how to thoroughly test it using Playwright. We will also explore the significance of data-testid attributes in testing and guide you through setting up Playwright for testing and running your tests with various methods.</p><h3>Form Component Explanation</h3><p>Below is the Form component we will be testing. It allows users to input items, submit them, and dynamically update a list on the page.</p><pre>&quot;use client&quot;;<br>import { useState } from &quot;react&quot;;<br><br>export default function Form() {<br>  const [items, setItems] = useState&lt;string[]&gt;([]);<br>  const [inputValue, setInputValue] = useState(&quot;&quot;);<br><br>  return (<br>    &lt;&gt;<br>      &lt;form<br>        onSubmit={(e) =&gt; {<br>          e.preventDefault();<br>          setItems([...items, inputValue]);<br>          setInputValue(&quot;&quot;);<br>        }}<br>        className=&quot;space-x-2&quot;<br>      &gt;<br>        &lt;label htmlFor=&quot;item&quot;&gt;Item:&lt;/label&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          name=&quot;item&quot;<br>          id=&quot;item&quot;<br>          value={inputValue}<br>          onChange={(e) =&gt; setInputValue(e.target.value)}<br>          placeholder=&quot;Enter item&quot;<br>          className=&quot;text-black h-8 px-4 rounded-md outline-none&quot;<br>        /&gt;<br><br>        &lt;button<br>          className=&quot;bg-white h-8 px-4 rounded-md text-black&quot;<br>          type=&quot;submit&quot;<br>        &gt;<br>          Add<br>        &lt;/button&gt;<br>      &lt;/form&gt;<br>      &lt;ul data-testid=&quot;items-list&quot;&gt;<br>        {items.map((item, index) =&gt; (<br>          &lt;li key={index} data-testid=&quot;item&quot;&gt;<br>            {item}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>In this component:</p><ul><li>Users can type into an input field and submit items.</li><li>The submitted items are dynamically rendered in an unordered list (&lt;ul&gt;).</li><li>We use the data-testid attribute to help Playwright target and interact with specific elements in the test.</li></ul><p><strong>Home page:</strong></p><pre>import type { Metadata } from &quot;next&quot;;<br>import Link from &quot;next/link&quot;;<br><br>export const metadata: Metadata = {<br>  title: &quot;Ozan&#39;s Next.js Starter&quot;,<br>};<br><br>export default function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1 className=&quot;text-2xl font-bold mb-4&quot;&gt;Home page&lt;/h1&gt;<br>      &lt;Link<br>        href=&quot;/form&quot;<br>        className=&quot;after:content-[&#39;_↗&#39;] text-xl bg-white px-4 py-2 rounded-md text-blue-500 hover:bg-blue-500 hover:text-white transition-colors duration-300&quot;<br>      &gt;<br>        Go to form page<br>      &lt;/Link&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Form Page:</strong></p><pre>import type { Metadata } from &quot;next&quot;;<br>import Form from &quot;@/test/app/components/Form&quot;;<br><br>export const metadata: Metadata = {<br>  title: &quot;Form page&quot;,<br>};<br><br>export default function FormPage() {<br>  return (<br>    &lt;div className=&quot;space-y-4&quot;&gt;<br>      &lt;h1 className=&quot;text-2xl font-bold&quot;&gt;Form page&lt;/h1&gt;<br>      &lt;Form /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Understanding data-testid Usage in Tests</h3><p>The data-testid attribute is often used as a stable hook to select DOM elements in tests. It allows us to reference specific elements within the component, regardless of how the component&#39;s internal structure or class names change over time.</p><p>In our case, we use data-testid in two places:</p><ol><li><strong>data-testid=&quot;items-list&quot;</strong>: This identifier helps us select the unordered list of items.</li><li><strong>data-testid=&quot;item&quot;</strong>: This identifier is applied to each individual list item in the form.</li></ol><p>These attributes are crucial for making our tests resilient to changes in UI layout or class names.</p><h3>Test Code Explanation</h3><p>Let’s now walk through the Playwright tests for the Form component. Here&#39;s the full test file, followed by an explanation of each part.</p><pre>import { test, expect } from &quot;@playwright/test&quot;;<br><br>test.describe(&quot;Home page&quot;, () =&gt; {<br>  test.beforeEach(async ({ page }) =&gt; {<br>    await page.goto(&quot;http://localhost:3000&quot;);<br>  });<br><br>  test(&quot;should have correct metadata and elements&quot;, async ({ page }) =&gt; {<br>    await expect(page).toHaveTitle(&quot;Ozan&#39;s Next.js Starter&quot;);<br><br>    await expect(<br>      page.getByRole(&quot;heading&quot;, { name: &quot;Home page&quot; })<br>    ).toBeVisible();<br><br>    await expect(<br>      page.getByRole(&quot;link&quot;, { name: &quot;Go to form page&quot; })<br>    ).toBeVisible();<br>  });<br><br>  test(&quot;should navigate to form page&quot;, async ({ page }) =&gt; {<br>    await page.getByRole(&quot;link&quot;, { name: &quot;Go to form page&quot; }).click();<br><br>    await expect(page).toHaveTitle(&quot;Form page&quot;);<br>  });<br>});<br><br>test.describe(&quot;Form page&quot;, () =&gt; {<br>  test.beforeEach(async ({ page }) =&gt; {<br>    await page.goto(&quot;http://localhost:3000/form&quot;);<br>  });<br><br>  test(&quot;should have correct metadata and elements&quot;, async ({ page }) =&gt; {<br>    await expect(page).toHaveTitle(&quot;Form page&quot;);<br><br>    await expect(<br>      page.getByRole(&quot;heading&quot;, { name: &quot;Form page&quot; })<br>    ).toBeVisible();<br><br>    await expect(page.getByRole(&quot;textbox&quot;, { name: &quot;Item:&quot; })).toBeVisible();<br><br>    await expect(page.getByLabel(&quot;Item:&quot;)).toBeVisible();<br><br>    await expect(page.getByPlaceholder(&quot;Enter item&quot;)).toBeVisible();<br><br>    await expect(page.getByRole(&quot;button&quot;, { name: &quot;Add&quot; })).toBeVisible();<br><br>    await expect(page.getByTestId(&quot;items-list&quot;)).toHaveText(&quot;&quot;);<br>  });<br><br>  test(&quot;should have empty items list&quot;, async ({ page }) =&gt; {<br>    const itemsList = page.getByTestId(&quot;items-list&quot;);<br><br>    await expect(itemsList).toBeEmpty();<br>  });<br><br>  test(&quot;should add item to the list&quot;, async ({ page }) =&gt; {<br>    const input = page.getByPlaceholder(&quot;Enter item&quot;);<br><br>    await input.fill(&quot;Test item 1&quot;);<br><br>    await page.getByRole(&quot;button&quot;, { name: &quot;Add&quot; }).click();<br><br>    const item = page.getByTestId(&quot;item&quot;).nth(0);<br><br>    await expect(item).toHaveText(&quot;Test item 1&quot;);<br><br>    await expect(input).toBeEmpty();<br><br>    await expect(page.getByTestId(&quot;items-list&quot;)).not.toBeEmpty();<br>  });<br>});</pre><h4>1. beforeEach Hook</h4><p>In each test, we use the beforeEach hook to navigate to the form page before any assertions are made. This ensures that every test starts on a fresh page.</p><pre>test.beforeEach(async ({ page }) =&gt; {<br>  await page.goto(&quot;http://localhost:3000/form&quot;);<br>});</pre><h4>2. Metadata and Element Visibility Test</h4><p>This test checks that the correct title and elements exist on the form page. We ensure that the page title, input field, label, placeholder text, and button are visible.</p><pre>test(&quot;should have correct metadata and elements&quot;, async ({ page }) =&gt; {<br>  await expect(page).toHaveTitle(&quot;Form page&quot;);<br>  await expect(page.getByRole(&quot;heading&quot;, { name: &quot;Form page&quot; })).toBeVisible();<br>  await expect(page.getByTestId(&quot;items-list&quot;)).toHaveText(&quot;&quot;);<br>});</pre><h4>3. Empty Items List Test</h4><p>We verify that the items list is empty when the form is first loaded.</p><pre>test(&quot;should have empty items list&quot;, async ({ page }) =&gt; {<br>  const itemsList = page.getByTestId(&quot;items-list&quot;);<br>  await expect(itemsList).toBeEmpty();<br>});</pre><h4>4. Add Item to the List Test</h4><p>This test simulates filling in the input field, clicking the “Add” button, and checking that the new item is added to the list. It also ensures that the input field is cleared afterward.</p><pre>test(&quot;should add item to the list&quot;, async ({ page }) =&gt; {<br>  const input = page.getByPlaceholder(&quot;Enter item&quot;);<br>  await input.fill(&quot;Test item 1&quot;);<br>  await page.getByRole(&quot;button&quot;, { name: &quot;Add&quot; }).click();<br><br>  const item = page.getByTestId(&quot;item&quot;).nth(0);<br>  await expect(item).toHaveText(&quot;Test item 1&quot;);<br><br>  await expect(input).toBeEmpty();<br>  await expect(page.getByTestId(&quot;items-list&quot;)).not.toBeEmpty();<br>});</pre><p>This test leverages data-testid=&quot;item&quot; to check that the new item appears in the list.</p><h3>Playwright Setup and Execution</h3><p>To set up Playwright in your Next.js project, follow these steps:</p><ul><li><strong>Install Playwright</strong>: Use the following command to install Playwright:</li></ul><pre>pnpm create playwright</pre><ul><li><strong>Run Tests</strong>: To run the tests and view the results in the terminal, use:</li></ul><pre>pnpm exec playwright test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qb-K7mgKpcUbK_2xtMDg7Q.png" /></figure><ul><li><strong>Show Reports</strong>: To view test results in the browser, run:</li></ul><pre>pnpm exec playwright show-report</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bju9Aj14XxwnJFiMkSOLbA.png" /></figure><ul><li><strong>UI Mode</strong>: To run tests in interactive UI mode, use:</li></ul><pre>pnpm exec playwright test --ui</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKHYHzvJ1sXE0x-Mz4983g.png" /></figure><p>Additionally, you can streamline the testing process using the Playwright VS Code extension: <a href="https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright">VS Code Playwright Extension</a>.</p><h3>Conclusion</h3><p>In this guide, we explored how to test a form component using Playwright, utilizing data-testid attributes to ensure robust and stable tests. You learned how to set up Playwright in your Next.js project, write effective tests, and execute them via the terminal or UI. With these tools and techniques, you can confidently test your form and any other components in your application.</p><p><a href="https://medium.com/shsfwork">SHSF Work</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89fea1af78a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shsfwork/testing-a-next-js-form-component-with-playwright-89fea1af78a4">Testing a Next.js Form Component with Playwright</a> was originally published in <a href="https://medium.com/shsfwork">SHSF Work</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>