how to make server side component in react in javascript

React is a front-end library for building user interfaces, it is not intended to interact with the server directly. However, you can use a backend technology to build a server and have React communicate with that backend through HTTP requests. There are several server-side technologies to choose from like Node.js, Ruby on Rails, Django, ASP.NET, etc.

Here's a simple example of how to create a server-side component in React:

  1. Install necessary dependencies:
npm install express cors
25 chars
2 lines
  1. Create a server.js file with the following contents:
index.tsx
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/api/data', (req, res) => {
  const data = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Bob' },
  ];

  res.json({ data });
});

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
391 chars
19 lines
  1. Start the server by running node server.js in the terminal.

  2. In a React component, you can fetch the data from the backend API using the fetch method or any similar Ajax library like axios.

index.tsx
import { useEffect, useState } from 'react';

function ServerComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(data => setData(data.data))
      .catch(err => console.log(err));
  }, []);

  return (
    <div>
      {data.map(item => (
        <p key={item.id}>{`${item.id} - ${item.name}`}</p>
      ))}
    </div>
  );
}

export default ServerComponent;
447 chars
23 lines

This example shows how to create a simple backend API with Express that returns an array of objects. Then, in a React component, we use the fetch method to call that API and display the returned data on the page.

Note: This is a very basic example, and in real production applications, the setup may be more complex.

related categories

gistlibby LogSnag