<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>React &#8211; CodeFusionOnline</title>
	<atom:link href="https://blogs.codefusiononline.com/category/react/feed/" rel="self" type="application/rss+xml" />
	<link>https://blogs.codefusiononline.com</link>
	<description>CodeFusionOnline Blogs &#38; documentations</description>
	<lastBuildDate>Wed, 22 Jan 2025 09:46:34 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://blogs.codefusiononline.com/wp-content/uploads/2025/01/cropped-Codefusion_dark_logo_2-32x32.png</url>
	<title>React &#8211; CodeFusionOnline</title>
	<link>https://blogs.codefusiononline.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>To connect a React app to a database</title>
		<link>https://blogs.codefusiononline.com/to-connect-a-react-app-to-a-database/</link>
					<comments>https://blogs.codefusiononline.com/to-connect-a-react-app-to-a-database/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 22 Jan 2025 09:46:34 +0000</pubDate>
				<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://test.codebeans.online/?p=1006</guid>

					<description><![CDATA[Post Views: 1,918 To connect a React app to a database, you&#8217;ll need to integrate the frontend with a backend that manages the database connections (MongoDB, MySQL, SQLite). React doesn&#8217;t directly connect to databases; it communicates with a backend server (using Express, for example) that interacts with the database. Here&#8217;s a step-by-step guide to set [&#8230;]]]></description>
										<content:encoded><![CDATA[<div class="post-views content-post post-1006 entry-meta load-static">
				<span class="post-views-icon dashicons dashicons-chart-bar"></span> <span class="post-views-label">Post Views:</span> <span class="post-views-count">1,918</span>
			</div><p>To connect a React app to a database, you&#8217;ll need to integrate the frontend with a backend that manages the database connections (MongoDB, MySQL, SQLite). React doesn&#8217;t directly connect to databases; it communicates with a backend server (using Express, for example) that interacts with the database.</p>
<p>Here&#8217;s a step-by-step guide to set up a basic backend using Express for MongoDB, MySQL, and SQLite. The backend will expose APIs that your React frontend can call to interact with the database.</p>
<h3>1. <strong>Setting Up the Backend (Node.js + Express)</strong></h3>
<p>First, we&#8217;ll need to set up a Node.js backend with Express that connects to MongoDB, MySQL, and SQLite.</p>
<h4>Install the Necessary Packages</h4>
<p>You&#8217;ll need these dependencies:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash">npm init -y<br />
npm install express mongoose mysql2 sqlite3 cors dotenv<br />
</code></div>
</div>
<ul>
<li><code>express</code> for creating the backend API.</li>
<li><code>mongoose</code> for MongoDB interaction.</li>
<li><code>mysql2</code> for MySQL interaction.</li>
<li><code>sqlite3</code> for SQLite interaction.</li>
<li><code>cors</code> to handle cross-origin requests from the React frontend.</li>
<li><code>dotenv</code> to manage environment variables.</li>
</ul>
<h3>2. <strong>Setting Up MongoDB Connection</strong></h3>
<h4>MongoDB Setup</h4>
<p>You need MongoDB running locally or you can use a cloud service like <a href="https://www.mongodb.com/cloud/atlas" target="_new" rel="noopener nofollow">MongoDB Atlas</a>.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-comment">// server.js (Backend for MongoDB)</span><br />
<span class="hljs-built_in">require</span>(<span class="hljs-string">'dotenv'</span>).<span class="hljs-title function_">config</span>();<br />
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);<br />
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);<br />
<span class="hljs-keyword">const</span> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>);</p>
<p><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>();<br />
app.<span class="hljs-title function_">use</span>(<span class="hljs-title function_">cors</span>());<br />
app.<span class="hljs-title function_">use</span>(express.<span class="hljs-title function_">json</span>());</p>
<p><span class="hljs-keyword">const</span> mongoURI = process.<span class="hljs-property">env</span>.<span class="hljs-property">MONGO_URI</span>; <span class="hljs-comment">// Example: 'mongodb://localhost:27017/mydb'</span></p>
<p>mongoose.<span class="hljs-title function_">connect</span>(mongoURI, { <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span> })<br />
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'MongoDB connected'</span>))<br />
  .<span class="hljs-title function_">catch</span>(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'MongoDB connection error:'</span>, err));</p>
<p>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">'/data'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {<br />
  <span class="hljs-comment">// You can replace this with actual MongoDB model operations.</span><br />
  res.<span class="hljs-title function_">json</span>({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Hello from MongoDB'</span> });<br />
});</p>
<p>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">5000</span>, <span class="hljs-function">() =&gt;</span> {<br />
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Server is running on port 5000'</span>);<br />
});<br />
</code></div>
</div>
<h4>.env file for MongoDB</h4>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">dotenv</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-dotenv">MONGO_URI=mongodb://localhost:27017/mydb<br />
</code></div>
</div>
<h3>3. <strong>Setting Up MySQL Connection</strong></h3>
<h4>MySQL Setup</h4>
<p>Install MySQL locally or use a cloud provider like <a href="https://aws.amazon.com/rds/" target="_new" rel="noopener nofollow">Amazon RDS</a>.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-comment">// server.js (Backend for MySQL)</span><br />
<span class="hljs-keyword">const</span> mysql = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mysql2'</span>);</p>
<p><span class="hljs-comment">// Create MySQL connection</span><br />
<span class="hljs-keyword">const</span> db = mysql.<span class="hljs-title function_">createConnection</span>({<br />
  <span class="hljs-attr">host</span>: <span class="hljs-string">'localhost'</span>,<br />
  <span class="hljs-attr">user</span>: <span class="hljs-string">'root'</span>,<br />
  <span class="hljs-attr">password</span>: <span class="hljs-string">'password'</span>,<br />
  <span class="hljs-attr">database</span>: <span class="hljs-string">'test_db'</span>,<br />
});</p>
<p>db.<span class="hljs-title function_">connect</span>(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {<br />
  <span class="hljs-keyword">if</span> (err) {<br />
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'MySQL connection error:'</span>, err);<br />
    <span class="hljs-keyword">return</span>;<br />
  }<br />
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'MySQL connected'</span>);<br />
});</p>
<p>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">'/mysql'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {<br />
  db.<span class="hljs-title function_">query</span>(<span class="hljs-string">'SELECT * FROM users'</span>, <span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> {<br />
    <span class="hljs-keyword">if</span> (err) {<br />
      res.<span class="hljs-title function_">status</span>(<span class="hljs-number">500</span>).<span class="hljs-title function_">json</span>({ <span class="hljs-attr">error</span>: <span class="hljs-string">'Database error'</span> });<br />
    } <span class="hljs-keyword">else</span> {<br />
      res.<span class="hljs-title function_">json</span>(results);<br />
    }<br />
  });<br />
});<br />
</code></div>
</div>
<h3>4. <strong>Setting Up SQLite Connection</strong></h3>
<h4>SQLite Setup</h4>
<p>SQLite is a serverless database. You only need to install the <code>sqlite3</code> package.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-comment">// server.js (Backend for SQLite)</span><br />
<span class="hljs-keyword">const</span> sqlite3 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'sqlite3'</span>).<span class="hljs-title function_">verbose</span>();</p>
<p><span class="hljs-comment">// Create a new SQLite database (or open an existing one)</span><br />
<span class="hljs-keyword">const</span> db = <span class="hljs-keyword">new</span> sqlite3.<span class="hljs-title class_">Database</span>(<span class="hljs-string">'./mydb.sqlite'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {<br />
  <span class="hljs-keyword">if</span> (err) {<br />
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'SQLite connection error:'</span>, err);<br />
    <span class="hljs-keyword">return</span>;<br />
  }<br />
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'SQLite connected'</span>);<br />
});</p>
<p>app.<span class="hljs-title function_">get</span>(<span class="hljs-string">'/sqlite'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {<br />
  db.<span class="hljs-title function_">all</span>(<span class="hljs-string">'SELECT * FROM users'</span>, <span class="hljs-function">(<span class="hljs-params">err, rows</span>) =&gt;</span> {<br />
    <span class="hljs-keyword">if</span> (err) {<br />
      res.<span class="hljs-title function_">status</span>(<span class="hljs-number">500</span>).<span class="hljs-title function_">json</span>({ <span class="hljs-attr">error</span>: <span class="hljs-string">'Database error'</span> });<br />
    } <span class="hljs-keyword">else</span> {<br />
      res.<span class="hljs-title function_">json</span>(rows);<br />
    }<br />
  });<br />
});<br />
</code></div>
</div>
<h3>5. <strong>Connecting the React Frontend</strong></h3>
<h4>Setting Up React to Fetch Data</h4>
<p>In your React app, you can fetch data from the APIs that the backend exposes. For example:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div></div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash">npx create-react-app frontend<br />
<span class="hljs-built_in">cd</span> frontend<br />
npm start<br />
</code></div>
</div>
<p>Create a file called <code>App.js</code> in the <code>src</code> folder:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span>, { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;</p>
<p><span class="hljs-keyword">const</span> <span class="hljs-title function_">App</span> = () =&gt; {<br />
  <span class="hljs-keyword">const</span> [data, setData] = <span class="hljs-title function_">useState</span>(<span class="hljs-literal">null</span>);</p>
<p>  <span class="hljs-title function_">useEffect</span>(<span class="hljs-function">() =&gt;</span> {<br />
    <span class="hljs-comment">// Change this URL based on which database you want to interact with</span><br />
    <span class="hljs-title function_">fetch</span>(<span class="hljs-string">'http://localhost:5000/data'</span>) <span class="hljs-comment">// MongoDB API endpoint</span><br />
      .<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.<span class="hljs-title function_">json</span>())<br />
      .<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-title function_">setData</span>(data.<span class="hljs-property">message</span>));<br />
  }, []);</p>
<p>  <span class="hljs-keyword">return</span> (<br />
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><br />
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{data ? data : 'Loading...'}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><br />
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br />
  );<br />
};</p>
<p><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">App</span>;<br />
</code></div>
</div>
<h3>6. <strong>Running the App</strong></h3>
<ol>
<li>Start your backend server:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash">node server.js<br />
</code></div>
</div>
</li>
<li>Start your React app:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash">npm start<br />
</code></div>
</div>
</li>
<li>Open your browser and go to <code>http://localhost:3000</code> to see the React app displaying data from the backend.</li>
</ol>
<h3>Summary of Steps</h3>
<ol>
<li><strong>Backend Setup</strong>:
<ul>
<li>Install the necessary packages (<code>express</code>, <code>mongoose</code>, <code>mysql2</code>, <code>sqlite3</code>, <code>cors</code>, <code>dotenv</code>).</li>
<li>Set up the database connections (MongoDB, MySQL, SQLite) in the backend using Express.</li>
<li>Expose API routes to interact with the database.</li>
</ul>
</li>
<li><strong>Frontend Setup</strong>:
<ul>
<li>Set up a React app.</li>
<li>Use <code>fetch()</code> to interact with the backend API.</li>
</ul>
</li>
<li><strong>Run the Backend</strong>: Start the backend server (<code>node server.js</code>).</li>
<li><strong>Run the Frontend</strong>: Start the React app (<code>npm start</code>).</li>
</ol>
<p>This is a simple tutorial on connecting React with MongoDB, MySQL, and SQLite via a backend. Depending on your use case, you may need to adjust the database queries, error handling, and API structure.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.codefusiononline.com/to-connect-a-react-app-to-a-database/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>To implement a threaded (nested) comment system in React</title>
		<link>https://blogs.codefusiononline.com/to-implement-a-threaded-nested-comment-system-in-react/</link>
					<comments>https://blogs.codefusiononline.com/to-implement-a-threaded-nested-comment-system-in-react/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 22 Jan 2025 09:39:50 +0000</pubDate>
				<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://test.codebeans.online/?p=1002</guid>

					<description><![CDATA[Post Views: 1,911 To implement a threaded (nested) comment system in React with backend functionality for managing comments (approve, remove, mark as spam, edit, etc.) and storing them in a database, follow these steps: 1. Frontend (React) a. Setting up the Comment Form: Create a form to submit comments and replies. You may need separate [&#8230;]]]></description>
										<content:encoded><![CDATA[<div class="post-views content-post post-1002 entry-meta load-static">
				<span class="post-views-icon dashicons dashicons-chart-bar"></span> <span class="post-views-label">Post Views:</span> <span class="post-views-count">1,911</span>
			</div><p>To implement a threaded (nested) comment system in React with backend functionality for managing comments (approve, remove, mark as spam, edit, etc.) and storing them in a database, follow these steps:</p>
<h3>1. <strong>Frontend (React)</strong></h3>
<h4>a. <strong>Setting up the Comment Form:</strong></h4>
<p>Create a form to submit comments and replies. You may need separate components for displaying the main comment form and the reply form.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">jsx</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"><span class="hljs-comment">// CommentForm.jsx</span><br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span>, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;</code></code><span class="hljs-keyword">function</span> <span class="hljs-title function_">CommentForm</span>(<span class="hljs-params">{ parentId = <span class="hljs-literal">null</span>, onSubmit }</span>) {<br />
<span class="hljs-keyword">const</span> [commentText, setCommentText] = <span class="hljs-title function_">useState</span>(<span class="hljs-string">&#8221;</span>);</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">handleSubmit</span> = (<span class="hljs-params">e</span>) =&gt; {<br />
e.<span class="hljs-title function_">preventDefault</span>();<br />
<span class="hljs-title function_">onSubmit</span>({ <span class="hljs-attr">text</span>: commentText, parentId });<br />
<span class="hljs-title function_">setCommentText</span>(<span class="hljs-string">&#8221;</span>);<br />
};</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-keyword">return</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">textarea</span><br />
<span class="hljs-attr">value</span>=<span class="hljs-string">{commentText}</span><br />
<span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setCommentText(e.target.value)}<br />
placeholder={parentId ? &#8216;Reply to this comment&#8217; : &#8216;Add a comment&#8217;}<br />
/&gt;<br />
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&#8220;submit&#8221;</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span><br />
);<br />
}</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">CommentForm</span>;</p>
</div>
</div>
<h4>b. <strong>Displaying Comments with Threading:</strong></h4>
<p>To handle nested comments, you&#8217;ll need a recursive component to display comments and their replies.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">jsx</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"><span class="hljs-comment">// CommentList.jsx</span><br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">CommentForm</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'./CommentForm'</span>;</code></code><span class="hljs-keyword">function</span> <span class="hljs-title function_">Comment</span>(<span class="hljs-params">{ comment, onSubmit }</span>) {<br />
<span class="hljs-keyword">return</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginLeft:</span> <span class="hljs-attr">comment.parentId</span> ? &#8216;<span class="hljs-attr">20px</span>&#8216; <span class="hljs-attr">:</span> &#8216;<span class="hljs-attr">0</span>&#8216; }}&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{comment.text}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">CommentForm</span> <span class="hljs-attr">parentId</span>=<span class="hljs-string">{comment.id}</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{onSubmit}</span> /&gt;</span><br />
{comment.replies &amp;&amp; (<br />
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">marginLeft:</span> &#8216;<span class="hljs-attr">20px</span>&#8216; }}&gt;</span><br />
{comment.replies.map((reply) =&gt; (<br />
<span class="hljs-tag">&lt;<span class="hljs-name">Comment</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{reply.id}</span> <span class="hljs-attr">comment</span>=<span class="hljs-string">{reply}</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{onSubmit}</span> /&gt;</span><br />
))}<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span><br />
)}<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br />
);<br />
}</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-keyword">function</span> <span class="hljs-title function_">CommentList</span>(<span class="hljs-params">{ comments, onSubmit }</span>) {<br />
<span class="hljs-keyword">return</span> comments.<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">comment</span>) =&gt;</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Comment</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{comment.id}</span> <span class="hljs-attr">comment</span>=<span class="hljs-string">{comment}</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{onSubmit}</span> /&gt;</span></span><br />
));<br />
}</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">CommentList</span>;</p>
</div>
</div>
<h4>c. <strong>Main Component to Manage Comments:</strong></h4>
<p>This component will handle fetching and submitting comments to the backend.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">jsx</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"><span class="hljs-comment">// CommentsSection.jsx</span><br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span>, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">CommentForm</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'./CommentForm'</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">CommentList</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'./CommentList'</span>;</code></code><span class="hljs-keyword">function</span> <span class="hljs-title function_">CommentsSection</span>(<span class="hljs-params">{ postId }</span>) {<br />
<span class="hljs-keyword">const</span> [comments, setComments] = <span class="hljs-title function_">useState</span>([]);</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-title function_">useEffect</span>(<span class="hljs-function">() =&gt;</span> {<br />
<span class="hljs-comment">// Fetch comments from the backend</span><br />
<span class="hljs-title function_">fetch</span>(<span class="hljs-string">`/api/comments?postId=<span class="hljs-subst">${postId}</span>`</span>)<br />
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.<span class="hljs-title function_">json</span>())<br />
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-title function_">setComments</span>(data));<br />
}, [postId]);</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">handleNewComment</span> = (<span class="hljs-params">newComment</span>) =&gt; {<br />
<span class="hljs-comment">// Submit new comment to the backend</span><br />
<span class="hljs-title function_">fetch</span>(<span class="hljs-string">&#8216;/api/comments&#8217;</span>, {<br />
<span class="hljs-attr">method</span>: <span class="hljs-string">&#8216;POST&#8217;</span>,<br />
<span class="hljs-attr">body</span>: <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(newComment),<br />
<span class="hljs-attr">headers</span>: {<br />
<span class="hljs-string">&#8216;Content-Type&#8217;</span>: <span class="hljs-string">&#8216;application/json&#8217;</span>,<br />
},<br />
})<br />
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.<span class="hljs-title function_">json</span>())<br />
.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-title function_">setComments</span>(<span class="hljs-function">(<span class="hljs-params">prevComments</span>) =&gt;</span> [&#8230;prevComments, data]));<br />
};</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-keyword">return</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">CommentForm</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleNewComment}</span> /&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">CommentList</span> <span class="hljs-attr">comments</span>=<span class="hljs-string">{comments}</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleNewComment}</span> /&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br />
);<br />
}</p>
<p><code class="!whitespace-pre hljs language-jsx"><code class="!whitespace-pre hljs language-jsx"></code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">CommentsSection</span>;</p>
</div>
</div>
<h3>2. <strong>Backend (Node.js with Express Example)</strong></h3>
<h4>a. <strong>Setting up the Database:</strong></h4>
<p>You will need a database table to store the comments. Here’s an example schema using MySQL or any relational database:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">sql</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> comments (<br />
id <span class="hljs-type">INT</span> AUTO_INCREMENT <span class="hljs-keyword">PRIMARY</span> KEY,<br />
post_id <span class="hljs-type">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span>,<br />
parent_id <span class="hljs-type">INT</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">NULL</span>,<br />
user_id <span class="hljs-type">INT</span>,<br />
text TEXT,<br />
status ENUM(<span class="hljs-string">'pending'</span>, <span class="hljs-string">'approved'</span>, <span class="hljs-string">'spam'</span>, <span class="hljs-string">'removed'</span>) <span class="hljs-keyword">DEFAULT</span> <span class="hljs-string">'pending'</span>,<br />
created_at <span class="hljs-type">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-built_in">CURRENT_TIMESTAMP</span>,<br />
<span class="hljs-keyword">FOREIGN</span> KEY (parent_id) <span class="hljs-keyword">REFERENCES</span> comments(id) <span class="hljs-keyword">ON</span> <span class="hljs-keyword">DELETE</span> CASCADE<br />
);<br />
</code></div>
</div>
<ul>
<li><code>parent_id</code>: used for nesting replies.</li>
<li><code>status</code>: used to track comment status (approved, spam, etc.).</li>
</ul>
<h4>b. <strong>Setting up Express Routes:</strong></h4>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-comment">// server.js</span><br />
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);<br />
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'body-parser'</span>);<br />
<span class="hljs-keyword">const</span> mysql = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mysql'</span>);</code></code><span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>();<br />
app.<span class="hljs-title function_">use</span>(bodyParser.<span class="hljs-title function_">json</span>());</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">const</span> db = mysql.<span class="hljs-title function_">createConnection</span>({<br />
<span class="hljs-attr">host</span>: <span class="hljs-string">&#8216;localhost&#8217;</span>,<br />
<span class="hljs-attr">user</span>: <span class="hljs-string">&#8216;root&#8217;</span>,<br />
<span class="hljs-attr">password</span>: <span class="hljs-string">&#8221;</span>,<br />
<span class="hljs-attr">database</span>: <span class="hljs-string">&#8216;blog_system&#8217;</span>,<br />
});</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-comment">// Fetch comments (including nested replies)</span><br />
app.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#8216;/api/comments&#8217;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {<br />
<span class="hljs-keyword">const</span> { postId } = req.<span class="hljs-property">query</span>;</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code>db.<span class="hljs-title function_">query</span>(<br />
<span class="hljs-string">&#8216;SELECT * FROM comments WHERE post_id = ? ORDER BY created_at&#8217;</span>,<br />
[postId],<br />
<span class="hljs-function">(<span class="hljs-params">err, results</span>) =&gt;</span> {<br />
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-comment">// Build nested comment structure</span><br />
<span class="hljs-keyword">const</span> comments = <span class="hljs-title function_">buildCommentTree</span>(results);<br />
res.<span class="hljs-title function_">json</span>(comments);<br />
}<br />
);<br />
});</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-comment">// Submit a new comment</span><br />
app.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#8216;/api/comments&#8217;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {<br />
<span class="hljs-keyword">const</span> { text, parentId, postId } = req.<span class="hljs-property">body</span>;<br />
<span class="hljs-keyword">const</span> userId = <span class="hljs-number">1</span>; <span class="hljs-comment">// You can replace with actual user ID logic</span></p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code>db.<span class="hljs-title function_">query</span>(<br />
<span class="hljs-string">&#8216;INSERT INTO comments (post_id, parent_id, user_id, text) VALUES (?, ?, ?, ?)&#8217;</span>,<br />
[postId, parentId, userId, text],<br />
<span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {<br />
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;<br />
res.<span class="hljs-title function_">status</span>(<span class="hljs-number">201</span>).<span class="hljs-title function_">json</span>({ <span class="hljs-attr">id</span>: result.<span class="hljs-property">insertId</span>, text, parentId });<br />
}<br />
);<br />
});</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-comment">// Manage comment status (approve, remove, spam, etc.)</span><br />
app.<span class="hljs-title function_">patch</span>(<span class="hljs-string">&#8216;/api/comments/:id/status&#8217;</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {<br />
<span class="hljs-keyword">const</span> { id } = req.<span class="hljs-property">params</span>;<br />
<span class="hljs-keyword">const</span> { status } = req.<span class="hljs-property">body</span>;</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code>db.<span class="hljs-title function_">query</span>(<br />
<span class="hljs-string">&#8216;UPDATE comments SET status = ? WHERE id = ?&#8217;</span>,<br />
[status, id],<br />
<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {<br />
<span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;<br />
res.<span class="hljs-title function_">status</span>(<span class="hljs-number">200</span>).<span class="hljs-title function_">send</span>(<span class="hljs-string">&#8216;Comment updated&#8217;</span>);<br />
}<br />
);<br />
});</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">buildCommentTree</span> = (<span class="hljs-params">comments</span>) =&gt; {<br />
<span class="hljs-keyword">const</span> commentMap = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();<br />
<span class="hljs-keyword">const</span> roots = [];</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code>comments.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">comment</span>) =&gt;</span> {<br />
comment.<span class="hljs-property">replies</span> = [];<br />
commentMap.<span class="hljs-title function_">set</span>(comment.<span class="hljs-property">id</span>, comment);</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">if</span> (comment.<span class="hljs-property">parent_id</span> === <span class="hljs-literal">null</span>) {<br />
roots.<span class="hljs-title function_">push</span>(comment);<br />
} <span class="hljs-keyword">else</span> {<br />
<span class="hljs-keyword">const</span> parent = commentMap.<span class="hljs-title function_">get</span>(comment.<span class="hljs-property">parent_id</span>);<br />
parent.<span class="hljs-property">replies</span>.<span class="hljs-title function_">push</span>(comment);<br />
}<br />
});</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">return</span> roots;<br />
};</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code>app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#8216;Server running on port 3000&#8217;</span>));</p>
</div>
</div>
<h3>3. <strong>Backend Management (Admin Panel)</strong></h3>
<p>You can create an admin panel where you can approve, remove, mark comments as spam, or edit them.</p>
<ul>
<li>Use a similar <code>PATCH</code> endpoint to manage comment status: <code>/api/comments/:id/status</code>.</li>
<li>Implement the ability to edit comments by updating the <code>text</code> field in the database.</li>
<li>You can use React components with buttons to call these endpoints.</li>
</ul>
<h3>4. <strong>Considerations for Scalability and Performance:</strong></h3>
<ul>
<li><strong>Pagination</strong>: Use pagination for fetching large numbers of comments.</li>
<li><strong>Caching</strong>: Cache comment data to reduce database load.</li>
<li><strong>Spam Detection</strong>: Integrate a spam detection API to automate the &#8220;mark as spam&#8221; functionality.</li>
<li><strong>Rate Limiting</strong>: Implement rate limiting to prevent spammy behavior on comment submission.</li>
</ul>
<p>This approach provides a fully functional threaded comment system with both frontend and backend components.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.codefusiononline.com/to-implement-a-threaded-nested-comment-system-in-react/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Creating a blog system in React</title>
		<link>https://blogs.codefusiononline.com/creating-a-blog-system-in-react/</link>
					<comments>https://blogs.codefusiononline.com/creating-a-blog-system-in-react/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 22 Jan 2025 09:33:09 +0000</pubDate>
				<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://test.codebeans.online/?p=999</guid>

					<description><![CDATA[Post Views: 1,917 Creating a blog system in React with features like author assignment, category and tag assignment, and the ability to create and edit posts requires a combination of a frontend (React) and backend (Node.js, Express, or similar) with a database (e.g., MongoDB, PostgreSQL, MySQL). Here&#8217;s an outline of how to implement it: 1. [&#8230;]]]></description>
										<content:encoded><![CDATA[<div class="post-views content-post post-999 entry-meta load-static">
				<span class="post-views-icon dashicons dashicons-chart-bar"></span> <span class="post-views-label">Post Views:</span> <span class="post-views-count">1,917</span>
			</div><p>Creating a blog system in React with features like author assignment, category and tag assignment, and the ability to create and edit posts requires a combination of a frontend (React) and backend (Node.js, Express, or similar) with a database (e.g., MongoDB, PostgreSQL, MySQL). Here&#8217;s an outline of how to implement it:</p>
<hr />
<h3>1. <strong>Setup the Project</strong></h3>
<h4>Frontend (React)</h4>
<ol>
<li>Initialize the React app:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash">npx create-react-app blog-system<br />
<span class="hljs-built_in">cd</span> blog-system<br />
</code></div>
</div>
</li>
<li>Install necessary packages:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div></div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash">npm install react-router-dom axios formik yup<br />
</code></div>
</div>
</li>
<li>Set up routing with React Router.</li>
</ol>
<h4>Backend</h4>
<ol>
<li>Initialize a Node.js project:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash"><span class="hljs-built_in">mkdir</span> blog-system-backend<br />
<span class="hljs-built_in">cd</span> blog-system-backend<br />
npm init -y<br />
</code></div>
</div>
</li>
<li>Install dependencies:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash">npm install express mongoose body-parser cors dotenv<br />
</code></div>
</div>
</li>
<li>Set up a basic Express server.</li>
</ol>
<hr />
<h3>2. <strong>Define Data Models</strong></h3>
<h4>Backend Models (e.g., using MongoDB)</h4>
<ul>
<li><strong>Author</strong>:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);<br />
<span class="hljs-keyword">const</span> <span class="hljs-title class_">AuthorSchema</span> = <span class="hljs-keyword">new</span> mongoose.<span class="hljs-title class_">Schema</span>({<br />
<span class="hljs-attr">name</span>: <span class="hljs-title class_">String</span>,<br />
<span class="hljs-attr">email</span>: <span class="hljs-title class_">String</span>,<br />
});<br />
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = mongoose.<span class="hljs-title function_">model</span>(<span class="hljs-string">'Author'</span>, <span class="hljs-title class_">AuthorSchema</span>);<br />
</code></div>
</div>
</li>
<li><strong>Category</strong>:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">const</span> <span class="hljs-title class_">CategorySchema</span> = <span class="hljs-keyword">new</span> mongoose.<span class="hljs-title class_">Schema</span>({<br />
<span class="hljs-attr">name</span>: <span class="hljs-title class_">String</span>,<br />
});<br />
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = mongoose.<span class="hljs-title function_">model</span>(<span class="hljs-string">'Category'</span>, <span class="hljs-title class_">CategorySchema</span>);<br />
</code></div>
</div>
</li>
<li><strong>Tag</strong>:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div></div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">const</span> <span class="hljs-title class_">TagSchema</span> = <span class="hljs-keyword">new</span> mongoose.<span class="hljs-title class_">Schema</span>({<br />
<span class="hljs-attr">name</span>: <span class="hljs-title class_">String</span>,<br />
});<br />
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = mongoose.<span class="hljs-title function_">model</span>(<span class="hljs-string">'Tag'</span>, <span class="hljs-title class_">TagSchema</span>);<br />
</code></div>
</div>
</li>
<li><strong>Blog Post</strong>:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">const</span> <span class="hljs-title class_">BlogPostSchema</span> = <span class="hljs-keyword">new</span> mongoose.<span class="hljs-title class_">Schema</span>({<br />
<span class="hljs-attr">title</span>: <span class="hljs-title class_">String</span>,<br />
<span class="hljs-attr">content</span>: <span class="hljs-title class_">String</span>,<br />
<span class="hljs-attr">author</span>: { <span class="hljs-attr">type</span>: mongoose.<span class="hljs-property">Schema</span>.<span class="hljs-property">Types</span>.<span class="hljs-property">ObjectId</span>, <span class="hljs-attr">ref</span>: <span class="hljs-string">'Author'</span> },<br />
<span class="hljs-attr">categories</span>: [{ <span class="hljs-attr">type</span>: mongoose.<span class="hljs-property">Schema</span>.<span class="hljs-property">Types</span>.<span class="hljs-property">ObjectId</span>, <span class="hljs-attr">ref</span>: <span class="hljs-string">'Category'</span> }],<br />
<span class="hljs-attr">tags</span>: [{ <span class="hljs-attr">type</span>: mongoose.<span class="hljs-property">Schema</span>.<span class="hljs-property">Types</span>.<span class="hljs-property">ObjectId</span>, <span class="hljs-attr">ref</span>: <span class="hljs-string">'Tag'</span> }],<br />
<span class="hljs-attr">createdAt</span>: { <span class="hljs-attr">type</span>: <span class="hljs-title class_">Date</span>, <span class="hljs-attr">default</span>: <span class="hljs-title class_">Date</span>.<span class="hljs-property">now</span> },<br />
});<br />
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = mongoose.<span class="hljs-title function_">model</span>(<span class="hljs-string">'BlogPost'</span>, <span class="hljs-title class_">BlogPostSchema</span>);<br />
</code></div>
</div>
</li>
</ul>
<hr />
<h3>3. <strong>Create API Endpoints</strong></h3>
<h4>Backend Routes</h4>
<ul>
<li><strong>Authors</strong>:
<ul>
<li><code>GET /authors</code>: Get all authors.</li>
<li><code>POST /authors</code>: Create an author.</li>
</ul>
</li>
<li><strong>Categories</strong>:
<ul>
<li><code>GET /categories</code>: Get all categories.</li>
<li><code>POST /categories</code>: Create a category.</li>
</ul>
</li>
<li><strong>Tags</strong>:
<ul>
<li><code>GET /tags</code>: Get all tags.</li>
<li><code>POST /tags</code>: Create a tag.</li>
</ul>
</li>
<li><strong>Blog Posts</strong>:
<ul>
<li><code>GET /posts</code>: Get all posts.</li>
<li><code>POST /posts</code>: Create a post.</li>
<li><code>PUT /posts/:id</code>: Edit a post.</li>
<li><code>DELETE /posts/:id</code>: Delete a post.</li>
</ul>
</li>
</ul>
<p>Example Express Route:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);<br />
<span class="hljs-keyword">const</span> <span class="hljs-title class_">BlogPost</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./models/BlogPost'</span>);<br />
<span class="hljs-keyword">const</span> router = express.<span class="hljs-title class_">Router</span>();</code></code>router.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#8216;/posts&#8217;</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {<br />
<span class="hljs-keyword">const</span> { title, content, author, categories, tags } = req.<span class="hljs-property">body</span>;<br />
<span class="hljs-keyword">try</span> {<br />
<span class="hljs-keyword">const</span> post = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BlogPost</span>({ title, content, author, categories, tags });<br />
<span class="hljs-keyword">await</span> post.<span class="hljs-title function_">save</span>();<br />
res.<span class="hljs-title function_">status</span>(<span class="hljs-number">201</span>).<span class="hljs-title function_">json</span>(post);<br />
} <span class="hljs-keyword">catch</span> (error) {<br />
res.<span class="hljs-title function_">status</span>(<span class="hljs-number">500</span>).<span class="hljs-title function_">json</span>({ <span class="hljs-attr">message</span>: error.<span class="hljs-property">message</span> });<br />
}<br />
});<code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = router;</p>
</div>
</div>
<hr />
<h3>4. <strong>Frontend Implementation</strong></h3>
<h4>Fetching Data</h4>
<ul>
<li>Use <code>axios</code> to interact with the backend API.</li>
</ul>
<h4>Create/Edit Blog Post Form</h4>
<ol>
<li>Use <code>Formik</code> for form handling and <code>Yup</code> for validation:
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;<br />
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Formik</span>, <span class="hljs-title class_">Form</span>, <span class="hljs-title class_">Field</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'formik'</span>;<br />
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> <span class="hljs-title class_">Yup</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'yup'</span>;<br />
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>;</code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">BlogForm</span> = () =&gt; {<br />
<span class="hljs-keyword">const</span> initialValues = {<br />
<span class="hljs-attr">title</span>: <span class="hljs-string">&#8221;</span>,<br />
<span class="hljs-attr">content</span>: <span class="hljs-string">&#8221;</span>,<br />
<span class="hljs-attr">author</span>: <span class="hljs-string">&#8221;</span>,<br />
<span class="hljs-attr">categories</span>: [],<br />
<span class="hljs-attr">tags</span>: [],<br />
};<code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">const</span> validationSchema = <span class="hljs-title class_">Yup</span>.<span class="hljs-title function_">object</span>({<br />
<span class="hljs-attr">title</span>: <span class="hljs-title class_">Yup</span>.<span class="hljs-title function_">string</span>().required(<span class="hljs-string">&#8216;Title is required&#8217;</span>),<br />
<span class="hljs-attr">content</span>: <span class="hljs-title class_">Yup</span>.<span class="hljs-title function_">string</span>().required(<span class="hljs-string">&#8216;Content is required&#8217;</span>),<br />
});</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">handleSubmit</span> = <span class="hljs-keyword">async</span> (<span class="hljs-params">values</span>) =&gt; {<br />
<span class="hljs-keyword">try</span> {<br />
<span class="hljs-keyword">await</span> axios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#8216;/posts&#8217;</span>, values);<br />
<span class="hljs-title function_">alert</span>(<span class="hljs-string">&#8216;Post created!&#8217;</span>);<br />
} <span class="hljs-keyword">catch</span> (error) {<br />
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error);<br />
}<br />
};</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">return</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Formik</span> <span class="hljs-attr">initialValues</span>=<span class="hljs-string">{initialValues}</span> <span class="hljs-attr">validationSchema</span>=<span class="hljs-string">{validationSchema}</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span><br />
{({ errors, touched }) =&gt; (<br />
<span class="hljs-tag">&lt;<span class="hljs-name">Form</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">Field</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&#8220;title&#8221;</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">&#8220;Title&#8221;</span> /&gt;</span><br />
{errors.title &amp;&amp; touched.title &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{errors.title}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}</span></p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-tag">&lt;<span class="hljs-name">Field</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&#8220;content&#8221;</span> <span class="hljs-attr">as</span>=<span class="hljs-string">&#8220;textarea&#8221;</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">&#8220;Content&#8221;</span> /&gt;</span><br />
{errors.content &amp;&amp; touched.content &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{errors.content}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-tag">&lt;<span class="hljs-name">Field</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&#8220;author&#8221;</span> <span class="hljs-attr">as</span>=<span class="hljs-string">&#8220;select&#8221;</span>&gt;</span><br />
{/* Fetch and map authors */}<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">Field</span>&gt;</span></p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-tag">&lt;<span class="hljs-name">Field</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&#8220;categories&#8221;</span> <span class="hljs-attr">as</span>=<span class="hljs-string">&#8220;select&#8221;</span> <span class="hljs-attr">multiple</span>&gt;</span><br />
{/* Fetch and map categories */}<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">Field</span>&gt;</span></p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-tag">&lt;<span class="hljs-name">Field</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&#8220;tags&#8221;</span> <span class="hljs-attr">as</span>=<span class="hljs-string">&#8220;select&#8221;</span> <span class="hljs-attr">multiple</span>&gt;</span><br />
{/* Fetch and map tags */}<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">Field</span>&gt;</span></p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&#8220;submit&#8221;</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">Form</span>&gt;</span><br />
)}<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">Formik</span>&gt;</span><br />
);<br />
};</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">BlogForm</span>;</p>
</div>
</div>
</li>
</ol>
<h4>Blog List and Edit Page</h4>
<ol>
<li>Display the list of blogs using <code>axios</code> to fetch <code>/posts</code>.</li>
<li>For editing, prefill the form with blog details.</li>
</ol>
<hr />
<h3>5. <strong>Styling and UI</strong></h3>
<ul>
<li>Use libraries like <code>Material-UI</code> or <code>Tailwind CSS</code> for a professional look.</li>
</ul>
<hr />
<h3>6. <strong>Deployment</strong></h3>
<ol>
<li>Deploy the backend to a service like Heroku, Vercel, or AWS.</li>
<li>Deploy the React frontend to Netlify, Vercel, or AWS Amplify.</li>
</ol>
<p>This approach creates a flexible, maintainable blog system with all the desired features!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.codefusiononline.com/creating-a-blog-system-in-react/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Integrating PayPal into a React application involves the following steps:</title>
		<link>https://blogs.codefusiononline.com/integrating-paypal-into-a-react-application-involves-the-following-steps/</link>
					<comments>https://blogs.codefusiononline.com/integrating-paypal-into-a-react-application-involves-the-following-steps/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 22 Jan 2025 07:32:41 +0000</pubDate>
				<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://test.codebeans.online/?p=993</guid>

					<description><![CDATA[Post Views: 1,902 Step 1: Set Up a PayPal Account Create a PayPal Developer Account Go to the PayPal Developer Portal and log in with your PayPal account. Create an App Navigate to the &#8220;My Apps &#38; Credentials&#8221; section. Create a new app under the &#8220;Sandbox&#8221; tab for testing. Obtain the Client ID and Secret [&#8230;]]]></description>
										<content:encoded><![CDATA[<div class="post-views content-post post-993 entry-meta load-static">
				<span class="post-views-icon dashicons dashicons-chart-bar"></span> <span class="post-views-label">Post Views:</span> <span class="post-views-count">1,902</span>
			</div><h3><strong>Step 1: Set Up a PayPal Account</strong></h3>
<ol>
<li><strong>Create a PayPal Developer Account</strong><br />
Go to the <a target="_new" rel="noopener">PayPal Developer Portal</a> and log in with your PayPal account.</li>
<li><strong>Create an App</strong>
<ul>
<li>Navigate to the &#8220;My Apps &amp; Credentials&#8221; section.</li>
<li>Create a new app under the &#8220;Sandbox&#8221; tab for testing.</li>
<li>Obtain the <strong>Client ID</strong> and <strong>Secret</strong> for integration.</li>
</ul>
</li>
</ol>
<hr />
<h3><strong>Step 2: Install PayPal SDK</strong></h3>
<p>PayPal provides a JavaScript SDK to integrate with its services.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">bash</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-bash">npm install @paypal/react-paypal-js<br />
</code></div>
</div>
<hr />
<h3><strong>Step 3: Add PayPal to Your React App</strong></h3>
<h4>1. <strong>Set Up PayPal Script Provider</strong></h4>
<p>Wrap your app with the <code>PayPalScriptProvider</code>. This loads the PayPal SDK globally.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;<br />
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">PayPalScriptProvider</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">"@paypal/react-paypal-js"</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">App</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>;</p>
<p><span class="hljs-keyword">const</span> <span class="hljs-title function_">PayPalApp</span> = () =&gt; (<br />
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">PayPalScriptProvider</span> <span class="hljs-attr">options</span>=<span class="hljs-string">{{</span> "<span class="hljs-attr">client-id</span>"<span class="hljs-attr">:</span> "<span class="hljs-attr">YOUR_CLIENT_ID</span>" }}&gt;</span><br />
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span><br />
  <span class="hljs-tag">&lt;/<span class="hljs-name">PayPalScriptProvider</span>&gt;</span></span><br />
);</p>
<p><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">PayPalApp</span>;<br />
</code></div>
</div>
<p>Replace <code>YOUR_CLIENT_ID</code> with the sandbox or production client ID from your PayPal app.</p>
<h4>2. <strong>Add PayPal Buttons</strong></h4>
<p>You can use the <code>PayPalButtons</code> component to display PayPal&#8217;s payment buttons.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;<br />
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">PayPalButtons</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">"@paypal/react-paypal-js"</span>;</p>
<p><span class="hljs-keyword">const</span> <span class="hljs-title function_">PayPalCheckout</span> = () =&gt; {<br />
  <span class="hljs-keyword">return</span> (<br />
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><br />
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Pay with PayPal<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><br />
      <span class="hljs-tag">&lt;<span class="hljs-name">PayPalButtons</span><br />
        <span class="hljs-attr">createOrder</span>=<span class="hljs-string">{(data,</span> <span class="hljs-attr">actions</span>) =&gt;</span> {<br />
          return actions.order.create({<br />
            purchase_units: [<br />
              {<br />
                amount: {<br />
                  value: "100.00", // Amount to be charged<br />
                },<br />
              },<br />
            ],<br />
          });<br />
        }}<br />
        onApprove={(data, actions) =&gt; {<br />
          return actions.order.capture().then((details) =&gt; {<br />
            alert(`Transaction completed by ${details.payer.name.given_name}`);<br />
            console.log(details);<br />
          });<br />
        }}<br />
        onError={(err) =&gt; {<br />
          console.error("PayPal Checkout Error:", err);<br />
        }}<br />
      /&gt;<br />
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br />
  );<br />
};</p>
<p><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">PayPalCheckout</span>;<br />
</code></div>
</div>
<hr />
<h3><strong>Step 4: Test in Sandbox</strong></h3>
<ol>
<li>Use the sandbox account details from your PayPal Developer Dashboard to test payments.</li>
<li>Click the PayPal button and follow the process to simulate a payment.</li>
</ol>
<hr />
<h3><strong>Step 5: Deploy to Production</strong></h3>
<ol>
<li>Replace the sandbox <code>client-id</code> with the production <code>client-id</code> in <code>PayPalScriptProvider</code>.</li>
<li>Test thoroughly in production mode.</li>
</ol>
<hr />
<h3><strong>Optional: Customize Buttons</strong></h3>
<p>The <code>PayPalButtons</code> component accepts additional props for customization.</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript">&lt;<span class="hljs-title class_">PayPalButtons</span><br />
  style={{<br />
    <span class="hljs-attr">layout</span>: <span class="hljs-string">"vertical"</span>,<br />
    <span class="hljs-attr">color</span>: <span class="hljs-string">"blue"</span>,<br />
    <span class="hljs-attr">shape</span>: <span class="hljs-string">"pill"</span>,<br />
    <span class="hljs-attr">label</span>: <span class="hljs-string">"checkout"</span>,<br />
  }}<br />
  fundingSource=<span class="hljs-string">"paypal"</span><br />
/&gt;<br />
</code></div>
</div>
<hr />
<h3><strong>Advanced Features</strong></h3>
<ol>
<li><strong>Server-Side Integration</strong><br />
For more secure processing, you can use PayPal&#8217;s server-side APIs to handle orders and transactions.</li>
<li><strong>Subscriptions</strong><br />
PayPal supports recurring payments. You can configure subscription buttons with <code>subscription_id</code>.</li>
<li><strong>Webhooks</strong><br />
Set up PayPal webhooks to track payment status updates automatically.</li>
</ol>
<hr />
<h3><strong>Full Example Code</strong></h3>
<p><strong>App.js</strong></p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;<br />
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">PayPalScriptProvider</span>, <span class="hljs-title class_">PayPalButtons</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">"@paypal/react-paypal-js"</span>;</p>
<p><span class="hljs-keyword">const</span> <span class="hljs-title function_">App</span> = () =&gt; (<br />
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">PayPalScriptProvider</span> <span class="hljs-attr">options</span>=<span class="hljs-string">{{</span> "<span class="hljs-attr">client-id</span>"<span class="hljs-attr">:</span> "<span class="hljs-attr">YOUR_CLIENT_ID</span>" }}&gt;</span><br />
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><br />
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>React PayPal Integration<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><br />
      <span class="hljs-tag">&lt;<span class="hljs-name">PayPalButtons</span><br />
        <span class="hljs-attr">createOrder</span>=<span class="hljs-string">{(data,</span> <span class="hljs-attr">actions</span>) =&gt;</span> {<br />
          return actions.order.create({<br />
            purchase_units: [<br />
              {<br />
                amount: { value: "50.00" },<br />
              },<br />
            ],<br />
          });<br />
        }}<br />
        onApprove={(data, actions) =&gt; {<br />
          return actions.order.capture().then((details) =&gt; {<br />
            console.log("Payment Approved:", details);<br />
            alert(`Transaction completed by ${details.payer.name.given_name}`);<br />
          });<br />
        }}<br />
        onError={(err) =&gt; {<br />
          console.error("Error:", err);<br />
        }}<br />
      /&gt;<br />
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span><br />
  <span class="hljs-tag">&lt;/<span class="hljs-name">PayPalScriptProvider</span>&gt;</span></span><br />
);</p>
<p><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">App</span>;<br />
</code></div>
</div>
<hr />
<h3><strong>Resources</strong></h3>
<ul>
<li><a target="_new" rel="noopener">PayPal React SDK Docs</a></li>
<li><a target="_new" rel="noopener">PayPal REST API Docs</a></li>
</ul>
<p>This tutorial provides a complete guide to setting up PayPal in React. Let me know if you need help with specific parts!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.codefusiononline.com/integrating-paypal-into-a-react-application-involves-the-following-steps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Manage Users by Roles &#038; Set Access Permissions in React</title>
		<link>https://blogs.codefusiononline.com/manage-users-by-roles-set-access-permissions-in-react/</link>
					<comments>https://blogs.codefusiononline.com/manage-users-by-roles-set-access-permissions-in-react/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 22 Jan 2025 07:23:48 +0000</pubDate>
				<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://test.codebeans.online/?p=989</guid>

					<description><![CDATA[Post Views: 1,907 Manage Users by Roles &#38; Set Access Permissions in React In this tutorial, you&#8217;ll learn how to implement role-based access control (RBAC) in a React application. We’ll cover the following steps: Setup Roles: Define user roles and permissions. Authentication: Login and store user information with roles. Access Control: Restrict access to pages [&#8230;]]]></description>
										<content:encoded><![CDATA[<div class="post-views content-post post-989 entry-meta load-static">
				<span class="post-views-icon dashicons dashicons-chart-bar"></span> <span class="post-views-label">Post Views:</span> <span class="post-views-count">1,907</span>
			</div><h3><strong>Manage Users by Roles &amp; Set Access Permissions in React</strong></h3>
<p>In this tutorial, you&#8217;ll learn how to implement role-based access control (RBAC) in a React application. We’ll cover the following steps:</p>
<ol>
<li><strong>Setup Roles</strong>: Define user roles and permissions.</li>
<li><strong>Authentication</strong>: Login and store user information with roles.</li>
<li><strong>Access Control</strong>: Restrict access to pages and components based on roles.</li>
<li><strong>Full Code Example</strong>: A working demo with roles like <code>Admin</code>, <code>Editor</code>, and <code>Viewer</code>.</li>
</ol>
<hr />
<h3><strong>Step 1: Setup Roles and Permissions</strong></h3>
<p>Define roles and permissions in a config file:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-comment">// roles.js</span><br />
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> <span class="hljs-title class_">Roles</span> = {<br />
<span class="hljs-attr">ADMIN</span>: <span class="hljs-string">"admin"</span>,<br />
<span class="hljs-attr">EDITOR</span>: <span class="hljs-string">"editor"</span>,<br />
<span class="hljs-attr">VIEWER</span>: <span class="hljs-string">"viewer"</span>,<br />
};</code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> <span class="hljs-title class_">Permissions</span> = {<br />
<span class="hljs-attr">CAN_EDIT</span>: [<span class="hljs-title class_">Roles</span>.<span class="hljs-property">ADMIN</span>, <span class="hljs-title class_">Roles</span>.<span class="hljs-property">EDITOR</span>],<br />
<span class="hljs-attr">CAN_VIEW</span>: [<span class="hljs-title class_">Roles</span>.<span class="hljs-property">ADMIN</span>, <span class="hljs-title class_">Roles</span>.<span class="hljs-property">EDITOR</span>, <span class="hljs-title class_">Roles</span>.<span class="hljs-property">VIEWER</span>],<br />
};</p>
</div>
</div>
<hr />
<h3><strong>Step 2: Authentication with Roles</strong></h3>
<p>Set up a basic authentication system with role-based login.</p>
<p><strong><code>AuthContext.js</code></strong>:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr">
<p><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span>, { createContext, useState, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;</code></p>
<p><span class="hljs-keyword">const</span> <span class="hljs-title class_">AuthContext</span> = <span class="hljs-title function_">createContext</span>();</p>
<p><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> <span class="hljs-title function_">AuthProvider</span> = (<span class="hljs-params">{ children }</span>) =&gt; {<br />
<span class="hljs-keyword">const</span> [user, setUser] = <span class="hljs-title function_">useState</span>(<span class="hljs-literal">null</span>);</p>
<p><span class="hljs-keyword">const</span> <span class="hljs-title function_">login</span> = (<span class="hljs-params">role</span>) =&gt; <span class="hljs-title function_">setUser</span>({ role }); <span class="hljs-comment">// Simulate login with a role</span><br />
<span class="hljs-keyword">const</span> <span class="hljs-title function_">logout</span> = () =&gt; <span class="hljs-title function_">setUser</span>(<span class="hljs-literal">null</span>);</p>
<p><span class="hljs-keyword">return</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AuthContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">user</span>, <span class="hljs-attr">login</span>, <span class="hljs-attr">logout</span> }}&gt;</span><br />
{children}<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">AuthContext.Provider</span>&gt;</span></span><br />
);<br />
};</p>
<p><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> <span class="hljs-title function_">useAuth</span> = () =&gt; <span class="hljs-title function_">useContext</span>(<span class="hljs-title class_">AuthContext</span>);</p>
</div>
</div>
<hr />
<h3><strong>Step 3: Create Protected Routes</strong></h3>
<p>Use role-based logic to guard routes.</p>
<p><strong><code>ProtectedRoute.js</code></strong>:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;<br />
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Navigate</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;<br />
<span class="hljs-keyword">import</span> { useAuth } <span class="hljs-keyword">from</span> <span class="hljs-string">"./AuthContext"</span>;</code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">ProtectedRoute</span> = (<span class="hljs-params">{ roles, children }</span>) =&gt; {<br />
<span class="hljs-keyword">const</span> { user } = <span class="hljs-title function_">useAuth</span>();</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">if</span> (!user) {<br />
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Navigate</span> <span class="hljs-attr">to</span>=<span class="hljs-string">&#8220;/login&#8221;</span> /&gt;</span></span>;<br />
}</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">if</span> (!roles.<span class="hljs-title function_">includes</span>(user.<span class="hljs-property">role</span>)) {<br />
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Access Denied<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>;<br />
}</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">return</span> children;<br />
};</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">ProtectedRoute</span>;</p>
</div>
</div>
<hr />
<h3><strong>Step 4: Implement Routing</strong></h3>
<p>Set up routes with access control.</p>
<p><strong><code>App.js</code></strong>:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;<br />
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">BrowserRouter</span> <span class="hljs-keyword">as</span> <span class="hljs-title class_">Router</span>, <span class="hljs-title class_">Routes</span>, <span class="hljs-title class_">Route</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;<br />
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AuthProvider</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">"./AuthContext"</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">ProtectedRoute</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"./ProtectedRoute"</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">LoginPage</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"./pages/LoginPage"</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">AdminPage</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"./pages/AdminPage"</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">EditorPage</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"./pages/EditorPage"</span>;<br />
<span class="hljs-keyword">import</span> <span class="hljs-title class_">ViewerPage</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"./pages/ViewerPage"</span>;</code></code><span class="hljs-keyword">function</span> <span class="hljs-title function_">App</span>() {<br />
<span class="hljs-keyword">return</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AuthProvider</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">Router</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">&#8220;/login&#8221;</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">LoginPage</span> /&gt;</span>} /&gt;<br />
<span class="hljs-tag">&lt;<span class="hljs-name">Route</span><br />
<span class="hljs-attr">path</span>=<span class="hljs-string">&#8220;/admin&#8221;</span><br />
<span class="hljs-attr">element</span>=<span class="hljs-string">{</span><br />
&lt;<span class="hljs-attr">ProtectedRoute</span> <span class="hljs-attr">roles</span>=<span class="hljs-string">{[</span>&#8220;<span class="hljs-attr">admin</span>&#8220;]}&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">AdminPage</span> /&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">ProtectedRoute</span>&gt;</span><br />
}<br />
/&gt;<br />
<span class="hljs-tag">&lt;<span class="hljs-name">Route</span><br />
<span class="hljs-attr">path</span>=<span class="hljs-string">&#8220;/editor&#8221;</span><br />
<span class="hljs-attr">element</span>=<span class="hljs-string">{</span><br />
&lt;<span class="hljs-attr">ProtectedRoute</span> <span class="hljs-attr">roles</span>=<span class="hljs-string">{[</span>&#8220;<span class="hljs-attr">admin</span>&#8220;, &#8220;<span class="hljs-attr">editor</span>&#8220;]}&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">EditorPage</span> /&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">ProtectedRoute</span>&gt;</span><br />
}<br />
/&gt;<br />
<span class="hljs-tag">&lt;<span class="hljs-name">Route</span><br />
<span class="hljs-attr">path</span>=<span class="hljs-string">&#8220;/viewer&#8221;</span><br />
<span class="hljs-attr">element</span>=<span class="hljs-string">{</span><br />
&lt;<span class="hljs-attr">ProtectedRoute</span> <span class="hljs-attr">roles</span>=<span class="hljs-string">{[</span>&#8220;<span class="hljs-attr">admin</span>&#8220;, &#8220;<span class="hljs-attr">editor</span>&#8220;, &#8220;<span class="hljs-attr">viewer</span>&#8220;]}&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">ViewerPage</span> /&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">ProtectedRoute</span>&gt;</span><br />
}<br />
/&gt;<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">Routes</span>&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">Router</span>&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">AuthProvider</span>&gt;</span></span><br />
);<br />
}</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">App</span>;</p>
</div>
</div>
<hr />
<h3><strong>Step 5: Role-Based Component Rendering</strong></h3>
<p>Use roles to show or hide elements.</p>
<p><strong><code>NavBar.js</code></strong>:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;<br />
<span class="hljs-keyword">import</span> { useAuth } <span class="hljs-keyword">from</span> <span class="hljs-string">"./AuthContext"</span>;</code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">NavBar</span> = () =&gt; {<br />
<span class="hljs-keyword">const</span> { user, logout } = <span class="hljs-title function_">useAuth</span>();</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">return</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&#8220;/viewer&#8221;</span>&gt;</span>Viewer Page<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><br />
{user?.role === &#8220;admin&#8221; &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&#8220;/admin&#8221;</span>&gt;</span>Admin Page<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>}<br />
{user?.role === &#8220;editor&#8221; &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&#8220;/editor&#8221;</span>&gt;</span>Editor Page<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>}<br />
{user ? (<br />
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{logout}</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br />
) : (<br />
<span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&#8220;/login&#8221;</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><br />
)}<br />
<span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span></span><br />
);<br />
};</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">NavBar</span>;</p>
</div>
</div>
<hr />
<h3><strong>Step 6: Full Code Example</strong></h3>
<p><strong><code>LoginPage.js</code></strong>:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="sticky top-9 md:top-[5.75rem]">
<div class="absolute bottom-0 right-2 flex h-9 items-center">
<div class="flex items-center rounded bg-token-sidebar-surface-primary px-2 font-sans text-xs text-token-text-secondary dark:bg-token-main-surface-secondary"></div>
</div>
</div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span>, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;<br />
<span class="hljs-keyword">import</span> { useAuth } <span class="hljs-keyword">from</span> <span class="hljs-string">"../AuthContext"</span>;</code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">LoginPage</span> = () =&gt; {<br />
<span class="hljs-keyword">const</span> { login } = <span class="hljs-title function_">useAuth</span>();<br />
<span class="hljs-keyword">const</span> [role, setRole] = <span class="hljs-title function_">useState</span>(<span class="hljs-string">&#8220;&#8221;</span>);</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">const</span> <span class="hljs-title function_">handleLogin</span> = () =&gt; {<br />
<span class="hljs-keyword">if</span> (role) <span class="hljs-title function_">login</span>(role);<br />
};</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">return</span> (<br />
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{role}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setRole(e.target.value)}&gt;<br />
<span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&#8220;&#8221;</span>&gt;</span>Select Role<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&#8220;admin&#8221;</span>&gt;</span>Admin<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&#8220;editor&#8221;</span>&gt;</span>Editor<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&#8220;viewer&#8221;</span>&gt;</span>Viewer<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br />
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleLogin}</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br />
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br />
);<br />
};</p>
<p><code class="!whitespace-pre hljs language-javascript"><code class="!whitespace-pre hljs language-javascript"></code></code><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">LoginPage</span>;</p>
</div>
</div>
<p><strong><code>AdminPage.js</code></strong>, <strong><code>EditorPage.js</code></strong>, and <strong><code>ViewerPage.js</code></strong>:</p>
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950">
<div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between rounded-t-md h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none">javascript</div>
<div class="overflow-y-auto p-4" dir="ltr">
<p><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;</code></p>
<p><span class="hljs-keyword">const</span> <span class="hljs-title function_">AdminPage</span> = () =&gt; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Admin Page &#8211; Only admins can access<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>;<br />
<span class="hljs-keyword">const</span> <span class="hljs-title function_">EditorPage</span> = () =&gt; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Editor Page &#8211; Admins and Editors can access<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>;<br />
<span class="hljs-keyword">const</span> <span class="hljs-title function_">ViewerPage</span> = () =&gt; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Viewer Page &#8211; All roles can access<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>;</p>
<p><span class="hljs-keyword">export</span> { <span class="hljs-title class_">AdminPage</span>, <span class="hljs-title class_">EditorPage</span>, <span class="hljs-title class_">ViewerPage</span> };</p>
</div>
</div>
<hr />
<h3><strong>Step 7: Deployment</strong></h3>
<p>Deploy your app using services like Netlify, Vercel, or AWS for hosting React apps.</p>
<p>With this setup, you now have a React application that manages user roles and sets access permissions dynamically. You can easily expand this by adding APIs for user management and storing roles in a database like MongoDB or Firebase.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.codefusiononline.com/manage-users-by-roles-set-access-permissions-in-react/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Online Food Delivery System with React</title>
		<link>https://blogs.codefusiononline.com/online-food-delivery-system-with-react/</link>
					<comments>https://blogs.codefusiononline.com/online-food-delivery-system-with-react/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 22 Jan 2025 07:14:53 +0000</pubDate>
				<category><![CDATA[React]]></category>
		<guid isPermaLink="false">https://test.codebeans.online/?p=987</guid>

					<description><![CDATA[Post Views: 1,950 Online Food Delivery System with React This tutorial covers creating an online food delivery system using React, Node.js, Express, and MongoDB. The system includes: Frontend: React app for users, admin, and restaurant login systems. Backend: Node.js with Express for RESTful API services. Database: MongoDB for managing users, items, categories, orders, and roles. [&#8230;]]]></description>
										<content:encoded><![CDATA[<div class="post-views content-post post-987 entry-meta load-static">
				<span class="post-views-icon dashicons dashicons-chart-bar"></span> <span class="post-views-label">Post Views:</span> <span class="post-views-count">1,950</span>
			</div><p data-pm-slice="1 1 []"><strong>Online Food Delivery System with React</strong></p>
<p>This tutorial covers creating an online food delivery system using React, Node.js, Express, and MongoDB. The system includes:</p>
<ol start="1" data-spread="false">
<li><strong>Frontend</strong>: React app for users, admin, and restaurant login systems.</li>
<li><strong>Backend</strong>: Node.js with Express for RESTful API services.</li>
<li><strong>Database</strong>: MongoDB for managing users, items, categories, orders, and roles.</li>
<li><strong>Payment Gateway</strong>: Integration using Stripe (or another payment service).</li>
</ol>
<div>
<hr />
</div>
<h3><strong>Step 1: Setup Project Structure</strong></h3>
<h4><strong>1.1 Install Node.js and Create a Project</strong></h4>
<pre><code># Install Node.js from https://nodejs.org/
npx create-react-app food-delivery-system
cd food-delivery-system</code></pre>
<h4><strong>1.2 Install Required Packages</strong></h4>
<p>Install dependencies for the frontend and backend.</p>
<pre><code># Frontend (React)
npm install react-router-dom axios redux react-redux

# Backend (Express + MongoDB)
npm install express mongoose body-parser cors bcrypt jsonwebtoken dotenv

# Payment Gateway (Stripe)
npm install stripe</code></pre>
<div>
<hr />
</div>
<h3><strong>Step 2: Backend Development</strong></h3>
<h4><strong>2.1 Setup Express Server</strong></h4>
<p>Create a folder <code>backend/</code> and initialize it.</p>
<pre><code>cd ..
mkdir backend
cd backend
npm init -y</code></pre>
<p>Create <code>server.js</code>.</p>
<pre><code>const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const connection = mongoose.connection;
connection.once('open', () =&gt; {
  console.log('MongoDB database connection established successfully');
});

// Example Routes
const userRoutes = require('./routes/users');
const adminRoutes = require('./routes/admin');
app.use('/api/users', userRoutes);
app.use('/api/admin', adminRoutes);

app.listen(PORT, () =&gt; {
  console.log(`Server is running on port: ${PORT}`);
});</code></pre>
<h4><strong>2.2 Define Models</strong></h4>
<p>Create a folder <code>models/</code> for MongoDB schemas.</p>
<p><strong>User.js</strong></p>
<pre><code>const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  role: { type: String, enum: ['user', 'restaurant', 'admin', 'superadmin'], default: 'user' },
  credit: { type: Number, default: 0 },
});

module.exports = mongoose.model('User', userSchema);</code></pre>
<p><strong>FoodItem.js</strong></p>
<pre><code>const mongoose = require('mongoose');

const foodItemSchema = new mongoose.Schema({
  name: { type: String, required: true },
  category: { type: String, enum: ['veg', 'non-veg', 'spicy'], required: true },
  price: { type: Number, required: true },
  addons: [{ name: String, price: Number }],
});

module.exports = mongoose.model('FoodItem', foodItemSchema);</code></pre>
<p><strong>Order.js</strong></p>
<pre><code>const mongoose = require('mongoose');

const orderSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
  items: [
    {
      item: { type: mongoose.Schema.Types.ObjectId, ref: 'FoodItem' },
      quantity: { type: Number, required: true },
      addons: [String],
    },
  ],
  totalAmount: { type: Number, required: true },
  status: { type: String, enum: ['pending', 'in-progress', 'delivered'], default: 'pending' },
});

module.exports = mongoose.model('Order', orderSchema);</code></pre>
<h4><strong>2.3 Implement Routes</strong></h4>
<p>Create a folder <code>routes/</code> and define routes for users, food items, orders, etc.</p>
<p>Example: <code>routes/users.js</code></p>
<pre><code>const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../models/User');

const router = express.Router();

// Register
router.post('/register', async (req, res) =&gt; {
  const { name, email, password, role } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);
  const newUser = new User({ name, email, password: hashedPassword, role });
  await newUser.save();
  res.status(201).send('User registered');
});

// Login
router.post('/login', async (req, res) =&gt; {
  const { email, password } = req.body;
  const user = await User.findOne({ email });
  if (!user || !(await bcrypt.compare(password, user.password))) {
    return res.status(400).send('Invalid credentials');
  }
  const token = jwt.sign({ id: user._id, role: user.role }, process.env.JWT_SECRET);
  res.json({ token });
});

module.exports = router;</code></pre>
<div>
<hr />
</div>
<h3><strong>Step 3: Frontend Development</strong></h3>
<h4><strong>3.1 Setup React Router</strong></h4>
<p>Add routes for user pages, admin dashboard, and restaurant dashboard.</p>
<p><strong>App.js</strong></p>
<pre><code>import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

import UserHome from './pages/UserHome';
import AdminDashboard from './pages/AdminDashboard';
import RestaurantDashboard from './pages/RestaurantDashboard';
import Login from './pages/Login';
import Register from './pages/Register';

function App() {
  return (
    &lt;Router&gt;
      &lt;Routes&gt;
        &lt;Route path="/" element={&lt;UserHome /&gt;} /&gt;
        &lt;Route path="/admin" element={&lt;AdminDashboard /&gt;} /&gt;
        &lt;Route path="/restaurant" element={&lt;RestaurantDashboard /&gt;} /&gt;
        &lt;Route path="/login" element={&lt;Login /&gt;} /&gt;
        &lt;Route path="/register" element={&lt;Register /&gt;} /&gt;
      &lt;/Routes&gt;
    &lt;/Router&gt;
  );
}

export default App;</code></pre>
<h4><strong>3.2 User Interfaces</strong></h4>
<p><strong>Login.js</strong></p>
<pre><code>import React, { useState } from 'react';
import axios from 'axios';

function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async (e) =&gt; {
    e.preventDefault();
    try {
      const response = await axios.post('/api/users/login', { email, password });
      localStorage.setItem('token', response.data.token);
      alert('Login successful');
    } catch (error) {
      alert('Login failed');
    }
  };

  return (
    &lt;form onSubmit={handleSubmit}&gt;
      &lt;input type="email" value={email} onChange={(e) =&gt; setEmail(e.target.value)} placeholder="Email" required /&gt;
      &lt;input type="password" value={password} onChange={(e) =&gt; setPassword(e.target.value)} placeholder="Password" required /&gt;
      &lt;button type="submit"&gt;Login&lt;/button&gt;
    &lt;/form&gt;
  );
}

export default Login;</code></pre>
<p>Continue developing the UI for <strong>AdminDashboard</strong>, <strong>RestaurantDashboard</strong>, and <strong>Order Management</strong>.</p>
<div>
<hr />
</div>
<h3><strong>Step 4: Payment Integration</strong></h3>
<p>Integrate Stripe or another payment service. Example with Stripe:</p>
<pre><code>const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

router.post('/create-payment-intent', async (req, res) =&gt; {
  const { amount } = req.body;
  const paymentIntent = await stripe.paymentIntents.create({
    amount,
    currency: 'usd',
  });
  res.send({ clientSecret: paymentIntent.client_secret });
});</code></pre>
<div>
<hr />
</div>
<h3><strong>Step 5: Deployment</strong></h3>
<p>Deploy the React frontend to Netlify or Vercel and the backend to Heroku, AWS, or another hosting platform.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blogs.codefusiononline.com/online-food-delivery-system-with-react/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
