Struggling to align elements in React/JS/M?

My challenge is aligning the elements in the middle of my page. I aim to have 3 elements per row, with n rows depending on the number of "VideoBox" components. It's crucial that these elements fit within the lettering of the P R O F E S S I O N A L P R O J E C T S title (refer to the image below).

As someone who struggles with JS/TS/CSS/React, any guidance would be greatly appreciated!

I've provided all the relevant code snippets below:

/*VideoFile.tsx*/
import React from 'react';
import './VideoFile.css'

export default function VideoBox({ name, image, link, release, popularity }) {
  return (
    <div>
        <div className="box">
            <img src={image} alt={name} />
        </div>
        <div className ="img-name">{name}</div>
    </div>
  );
};

export { VideoBox };
...Continued with other code snippets and explanations.

To visualize the current layout, here is an image for reference:

Click here to view the image (placeholder pictures shown)

Answer №1

To enhance the user experience, I prioritize leveraging MUI while minimizing the reliance on CSS styles until the foundational elements are in place and functioning as desired.

One suggestion is to transform your one-dimensional array of video files into a new two-dimensional grid (3 x N).

import { Grid, Container, Paper, Typography } from '@mui/material';

const testUrl =
  'https://fastly.picsum.photos/id/237/200/200.jpg?hmac=zHUGikXUDyLCCmvyww1izLK3R3k8oRYBRiTizZEdyfI';

// Sample data
const videoFiles = [
  {name: 'Awesome Adventure', imageUrl: testUrl, link: '#', release: '2023-01-01', popularity: 80},
  {name: 'Fantastic Journey', imageUrl: testUrl, link: '#', release: '2023-02-15', popularity: 92},
  {name: 'Epic Exploration', imageUrl: testUrl, link: '#', release: '2023-03-21', popularity: 65},
  {name: 'Amazing Discovery', imageUrl: testUrl, link: '#', release: '2023-04-10', popularity: 87},
  {name: 'Cool Quest', imageUrl: testUrl, link: '#', release: '2023-05-05', popularity: 75},
  {name: 'Unbelievable Voyage', imageUrl: testUrl, link: '#', release: '2023-06-18', popularity: 89},
  {name: 'Incredible Expedition', imageUrl: testUrl, link: '#', release: '2023-07-30', popularity: 78},
  {name: 'Exciting Trek', imageUrl: testUrl, link: '#', release: '2023-08-22', popularity: 94},
  {name: 'Breathtaking Safari', imageUrl: testUrl, link: '#', release: '2023-09-14', popularity: 82},
  {name: 'Adventurous Safari', imageUrl: testUrl, link: '#', release: '2023-10-09', popularity: 88},
];

const arrayToGrid = (arr, elementsPerRow) => {
  const result = [];
  for (let i = 0; i < arr.length; i += elementsPerRow) {
    result.push(arr.slice(i, i + elementsPerRow));
  }
  return result;
};

const videoGrid = arrayToGrid(videoFiles, 3);

// Component for displaying Video data with details
const VideoBox = ({ name, imageUrl }) => (
  <Paper
    elevation={3}
    style={{
      padding: 16,
      textAlign: 'center',
      display: 'flex',
      flexDirection: 'column',
    }}
  >
    <img
      src={imageUrl}
      alt={name}
      style={{ maxWidth: '100%', height: 'auto', marginBottom: 8 }}
    />
    <Typography variant='subtitle1'>{name}</Typography>
  </Paper>
);

// Main component rendering the grid
const Home = () => (
  <Container maxWidth='md' style={{ marginTop: 16 }}>
    <Grid container spacing={3}>
      {videoGrid.map((row) =>
        row.map((vidData, idx) => (
          <Grid key={idx} item xs={12} sm={4}>
            <VideoBox {...vidData} />
          </Grid>
        ))
      )}
    </Grid>
  </Container>
);

export default Home;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the React input value keep its value when the modal is re-rendered, despite the state being updated correctly?

Take a look at this sandbox link for the code snippet: Sandbox Showcased below is a table structure: https://i.sstatic.net/3F3Mc.png By clicking on the 'edit' button, a modal window opens up as shown below allowing you to edit input fields (onC ...

Navigating AJAX Pages - Maximize the Potential of #home and Other Sections

I am working on creating AJAX pages using a tutorial I found on Tutorialzine. The script I am using loads pages using AJAX but it requires specifying the page number in the URL like http://example.com/#page1 or http://example.com/#page2. Is there a way t ...

Tips for extracting data from a state-based object store in React?

Whenever I attempt to execute a PUT call, I fetch the data by id and save it in a state named "getData". While I am able to filter and map over this data, I face issues when trying to extract individual values. For instance, accessing getData.firstName res ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

retrieve the data-task-IDs from the rows within the table

I am currently working with a table that looks like this: <table id="tblTasks"> <thead> <tr> <th>Name</th> <th>Due</th> ...

Having trouble getting the Facebook like button to display on my website using an iframe in the markup

I gave it my all to try and get it to work, but unfortunately, I was unsuccessful. This is the approach I took. First, I followed the instructions provided on https://developers.facebook.com/docs/plugins/like-button. Next, I copied and pasted the iframe ...

Is there a way to modify the response code that has already been dispatched?

I wrote this code with the intention of sending response headers quickly: const http = require('http'); const fs = require('fs'); const server = http.createServer((req, res) => { fs.readFile(/*file path*/, 'utf8', (err, ...

Plaid webhook failing to activate

I've been struggling to set up Plaid transaction webhooks in an api, as I can't seem to get any webhooks to trigger. I followed the plaid quickstart code and included the webhook parameter: Plaid.create({ apiVersion: "v2", clientName: ...

What is the method for transforming a JavaScript array (without an object name) into JSON format (with an object name)?

Currently, I am using an ajax query to read a local csv file and then loading the extracted values into an array. This is how the string value appears in the csv file: "Tiger","Architect","800","DRP","5421" ...

Struggling with creating a CSS navigation bar, having issues with hover functionality

I have a question about the navigation menu I created using CSS. I have included a sub-menu that appears when hovering over the main menu item, along with a triangle created with CSS placed underneath the menu. You can view the sample code here: http://js ...

Is it advisable to opt for window.webkitRequestAnimationFrame over setInterval?

Trying to figure out the best method for moving game characters in my JavaScript game - should I go with window.webkitRequestAnimationFrame or stick with setInterval? Any advice is appreciated! ...

Nextjs: Issues with Dropdown functionality when using group and group-focus with TailwindCSS

My goal is to make an array visible once a button is clicked. By default, the array should be invisible, similar to drop-down menus in menu bars. I am utilizing the group and group-focus classes. While the array disappears as expected, it does not reappear ...

Having issues with AngularJS ng-if when implemented within a Form

Is there a way to hide my form after it has been submitted using ng-if? I am facing an issue where clicking the 'See' button toggles the form on and off, but the same functionality does not work with the 'Add' button. Any insights on wh ...

Is there a way to enable Tail Recursion Optimization in TypeScript?

const isPositive = (n: number) => n > 0; function fitsIn(dividend: number, divisor: number, count: number, accum: number): number { if (accum + divisor > dividend) { return count; } return ...

Calculating every number within a range of dates and storing them in the format of [day, hour]

Given two date pairs represented as numbers [hour, weekday], where hour ranges from 0-23 and weekday ranges from 1-7. I am tasked with generating all the hours in between each pair. For example, if given [13, 2] and [2, 3], the output would be: [13,2] [14 ...

Tooltips experience issues when interacting with elements that do not utilize the :active state

$(function () { $('[data-toggle="tooltip"]').tooltip() }) <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" ...

Send multiple input groups using Ajax POST requests

I need help setting up a form with 4 groups of checkboxes for refining search results. My goal is to send an array for each checkbox group that contains the IDs of the currently selected checkboxes. $.ajax({ url: "/stay_in_belfast/accommodation", t ...

The component encountered an error because the element type provided was not valid

I've encountered an error that has me stumped: https://i.sstatic.net/glSvr.png I've been trying to locate the HeaderSegment, but it seems to be missing from my project. I've checked for any imports, such as: import HeaderSegment from &apos ...

Tips for uploading a file with fetch

While I know this question has been asked before, none of the solutions seem to be working for me. Initially, I attempted to resolve the issue using axios, but it appears that there is a bug preventing me from utilizing it for file uploads. Therefore, I am ...

Automatically showcase images from a directory upon webpage loading

Is there a way to modify my code so that the images from the first directory are displayed on the page when it loads, instead of waiting for a menu option to be clicked? The page looks empty until a menu option is selected, and I would like the images to s ...