Using Redux with NextJs

I am working on a NextJs project right now and I am also using Redux with it. I notice that during build time, whatever is wrapped by Redux store doesn’t pre-render its content. I check by going to the ‘View page source’ and there are no pre-rendered data there. However, without being wrapped by the Redux store, the page will be populated with some data which is why I choose NextJs for my project. Can anyone explain to me why this happens and how to fix it when combining NextJs and Redux?

Thank you for your concern

Beginner tying to rebuild code with for loops instead of reduce method – not working

Challenge: Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.

After finding a solution using the reduce method, I tried to rebuild the code without using the reduce method – it didn’t work. Where did I go wrong? Can the desired outcome be achived using the rudimentary approach I tried?

Here’s the original solution.

function intersection1 (arrayOfArrays) {
    return arrayOfArrays.reduce((accumulator, currentValue) => {


      const newArr = [];

      accumulator.forEach((ele)=>{
        if (currentValue.includes(ele)) { 
          result.push(ele);
        };
      })
      return result;
    });
  }
  const arr1 = [5, 10, 15, 20];
  const arr2 = [15, 88, 1, 5, 7];
  const arr3 = [1, 10, 15, 5, 20];
  console.log(intersection1([arr1, arr2, arr3])); // should log: [5, 15]

I tried the following approach but it doesn’t work. It doesn’t log: [5, 15] but just: 1

function intersection (arrayOfArrays) {
    const newArr = [];
    let cache1 = [];
    let cache2 = [];
    let cache3 = [];

    for (let i = 0; i < arrayOfArrays.length; i++) {
      return cache1.push(arrayOfArrays[i]);
      
    }    

    for (let j = 1; j < arrayOfArrays.length; j++) {
      return cache2.push(arrayOfArrays[j]);

    }

    for (let n = 2; n <= arrayOfArrays.length; n++) {
      return cache3.push(arrayOfArrays[n]);

    }
    cache1.forEach((ele) => {
      if (cache2.includes(ele) && cache3.includes(ele)) {
        newArr.push(ele);
      }
    });
    return newArr;
  }

  const arr1 = [5, 10, 15, 20];
  const arr2 = [15, 88, 1, 5, 7];
  const arr3 = [1, 10, 15, 5, 20];
  console.log(intersection([arr1, arr2, arr3])); // should log: [5, 15]

How to tell where site content is being pulled from when it is loaded through javascript

I am trying to scrape some snow data from the mt bachelor website to further analyze and make predictions for avalanches from this page: https://www.mtbachelor.com/the-mountain/weather-operations/conditions-report/live-24-hour-weather

However when I click to view page source, none of the data is there. So I am assuming it is being pulled in from javascript some how.

I want to use php and curl to parse the page and save the snow data into a database. I know how to do that part. However since the page that I want to access does not show the data in the source code, is there a way to still scrape that information?

Reassigned NodeList in ForEach Loop with list.js

I’m using List.js to sort a HTML list.
The JS reorders the list items in the DOM.
Now I made elements in my list clickable and i need to use the (new) index of my list items.

Super Simple HTML setup:

<div id="mylist">
  <ul class="simple list">
    <li class="items">one</li>
    <li class="items">two</li>
    <li class="items">three</li>
    <li class="items">four</li>
  </ul>
</div>

JS

let nodeList = getUpdatedList();

function getUpdatedList () {
  return document.querySelectorAll('.items');
}

// here comes the List.js setup
const list = new List("mylist", { "some options" });

// and here I reassign the new List to the nodeList variable
list.on('updated', ()=>{
  nodeList = getUpdatedList();
})

// print the index on click
nodeList.forEach((item, index) => {
  item.addEventListener('click', () => {
    console.log(index);
  })
})

List.js works perfectly, the items are now reordered in the DOM after a sort method.
For example

  <ul class="simple list">
    <li class="items">three</li>
    <li class="items">four</li>
    <li class="items">two</li>
    <li class="items">one</li>
  </ul>

But when I click on the first item, the console still prints 4 (the old order) although I reassigned nodelist after list.js update.

Unable to read googlesheets from nodejs

I am trying to read a sheet from a multi-sheet google spreadsheet. I am using GoogleAuth API to authorise wuth the service account key. Please see the code snippet below

const auth = new google.auth.GoogleAuth({
    keyFile: credentials1,
    scopes: ['https://www.googleapis.com/auth/spreadsheets.readonly']
  })

const sheets = google.sheets({ version: 'v2', auth: auth })

const response = await sheets.spreadsheets.values.get({
      spreadsheetId,
      range,
      majorDimension: 'ROWS'
  }

I am getting the error :Error: ENAMETOOLONG: name too long, open”.

Trying to execute this nodejs script and getting error ‘Error: ENAMETOOLONG: name too long, open’

Need to update PSQL row of a composite type in golang with jack/pgx

I am trying to insert/update data in PostgreSQL using jackc/pgx into a table that has column of composite type. This is the table type written as a golan struct:

// Added this struct as a Types in PSQL
type DayPriceModel struct {
    Date                time.Time `json:"date"`
    High                float32   `json:"high"`
    Low                 float32   `json:"low"`
    Open                float32   `json:"open"`
    Close               float32   `json:"close"`
}

// The 2 columns in my table

type SecuritiesPriceHistoryModel struct {
    Symbol  string          `json:"symbol"`
    History []DayPriceModel `json:"history"`
}

The column history is an array of composite type which I have defined as DayPriceModel in PSQL. I want to append a new element to history in golang using jack/pgx

I have so far written the given code:

// The code for newType was generated by ChatGPT so it might or might not be correct. Feel free to overwrite this part.
newType, _ := pgtype.NewCompositeType("day_price_model", []pgtype.CompositeTypeField{
            {Name: "date", OID: pgtype.DateOID},
            {Name: "high", OID: pgtype.Float4OID},
            {Name: "low", OID: pgtype.Float4OID},
            {Name: "open", OID: pgtype.Float4OID},
            {Name: "close", OID: pgtype.Float4OID},
        }, (*pgtype.ConnInfo)(pool.Config().ConnConfig.TLSConfig.ClientCAs))

_, err = pool.Exec(context.Background(), `UPDATE equity.securities_price_history
SET history = $1::equity.day_price[] || history WHERE symbol = $2`,
composite_value_here, "something") // unable to form the composite_value_here variable

Using jack/pgx, how do I create a new composite value from a composite type to write in the PSQL query.

Docker | PermissionError: [Errno 13] Permission denied + command returned a non-zero code: 100

I have been working on a FastAI model and am now ready to deploy it. However, I’m facing difficulties in getting the model to work via Docker locally.

I’m at a loss as to what’s causing the problem and how to resolve it. I’ve little experience with Docker. Creating my own Dockerfile is new to me; so I may have left out obvious commands.

Dockerfile:

# Install image and dependencies
FROM python:3.9

# Set working directory
WORKDIR /app

# Copy the application files from the host to the container
COPY app.py /app/

# Install necessary packages
RUN apt-get update && 
    apt-get install -y --fix-missing && 
    pip install pip==20.2

# Install project dependencies
COPY requirements.txt /requirements.txt
RUN pip install -r /requirements.txt

# Download model artefacts from S3
RUN apt-get install -y awscli 
    && mkdir -p /models/ 
    && aws s3 cp s3://nihr-data-restricted/yasmine-batch3/PDL1_0.2_export.pkl /models/ 
    && aws s3 cp s3://nihr-data-restricted/yasmine-sftp2/model_3C_34_CELW_V_0.2_96_second.pth /models/

# Expose the port
EXPOSE 8000

# Run the application
CMD ["python", "/app/app.py"]

# docker run -p -i -t 8000:8000 pdl1_lung_image

Traceback:

Step 7/9 : RUN apt-get install -y awscli     && mkdir -p /models/     && aws s3 cp s3://foo/bar.pkl /models/     && aws s3 cp s3://foo/bar.pth /models/
 ---> Running in 7b2d18a2957a
Reading package lists...
Building dependency tree...
Reading state information...
The following additional packages will be installed:
...
[Errno 13] Permission denied: '/usr/lib/python3/dist-packages/pkg_resources/__pycache__/__init__.cpython-39.pyc.140347841853312'
...
E: Sub-process /usr/bin/dpkg returned an error code (1)
The command '/bin/sh -c apt-get install -y awscli     && mkdir -p /models/     && aws s3 cp s3://nihr-data-restricted/yasmine-batch3/PDL1_0.2_export.pkl /models/     && aws s3 cp s3://nihr-data-restricted/yasmine-sftp2/model_3C_34_CELW_V_0.2_96_second.pth /models/' returned a non-zero code: 100

Many of these occur: [Errno 13] Permission denied


Inserting user before failing Step didn’t work:

# Create a new user
RUN useradd -m -s /bin/bash user

# Give newuser all privileges
RUN usermod -aG sudo user

# Switch to user
USER user

Traceback:

Step 10/12 : RUN apt-get install -y awscli     && mkdir -p /models/     && aws s3 cp s3://nihr-data-restricted/yasmine-batch3/PDL1_0.2_export.pkl /models/     && aws s3 cp s3://nihr-data-restricted/yasmine-sftp2/model_3C_34_CELW_V_0.2_96_second.pth /models/
 ---> Running in 96d1e6f73307
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
The command '/bin/sh -c apt-get install -y awscli     && mkdir -p /models/     && aws s3 cp s3://nihr-data-restricted/yasmine-batch3/PDL1_0.2_export.pkl /models/     && aws s3 cp s3://nihr-data-restricted/yasmine-sftp2/model_3C_34_CELW_V_0.2_96_second.pth /models/' returned a non-zero code: 100

GitLab CI Mounted docker volumes stay empty in pipeline

I am having a problem with my GitLab pipeline when trying to mount a docker volume inside a container. Before I explain the problem, first I will describe my whole setup, because I think that is very essential to understand the problem, because I think that this is the reason why I am having this problem.

Setup

Okay, so to start off, I have a kubernetes cluster. This cluster runs my gitlab/gitlab-ee:15.8.0-ee.0 image. I installed a GitLab runner in this cluster as well, so that I am able to run pipelines of course. Then the last thing I installed is a docker instance, because I saw that you can mount the docker.sock from your host machine to the gitlab pipeline, but this is not recommended, because the entire cluster relies on that docker.sock, so I have another instance of docker running and I am mounting that docker.sock for pipelines only. These 3 deployments are used by me to run GitLab pipelines.

The problem

I am happy with the way everything is setup, but I think I am still missing some configuration, because the mounting of docker volumes are not working properly in pipelines. I have this script to test this, which contains this code:

image: docker:20.10.16-dind

variables:
  DOCKER_HOST: "tcp://docker-service:2375" # <-- Address to reach the docker instance from my cluster
  DOCKER_COMPOSE_CMD: "docker-compose -f docker-compose-test.yml"

  
stages:
  - test

test:
  stage: test
  script:
    - $DOCKER_COMPOSE_CMD down --volumes --remove-orphans
    - $DOCKER_COMPOSE_CMD build
    - $DOCKER_COMPOSE_CMD --env-file .env.pipeline up -d
    - $DOCKER_COMPOSE_CMD exec -T -e APP_ENV=testing laravel-api-test sh -c "ls"

With the following docker-compose-test.yml:

version: '3.7'
services:
  laravel-api-test:
    build:
      context: .
      dockerfile: docker/development/Dockerfile
    volumes:
      - .:/var/www/html
    environment:
    - COMPOSER_MEMORY_LIMIT=-1
    depends_on:
    - database-test
  database-test:
    image: postgres:15.1-alpine
    ports:
    - ${DB_PORT}:5432
    environment:
      POSTGRES_DB: ${DB_DATABASE}
      POSTGRES_PASSWORD: ${DB_PASSWORD_SECRET}
      POSTGRES_USER: ${DB_USERNAME_SECRET}
  redis-test:
    image: redis:7.0.8
    ports:
    - ${REDIS_PORT}:6379
networks:
  default:
    name: application

Now what this pipeline does, it builds the docker containers and then starts them. Then it runs the ls command which prints out all the files in the working-dir of the container. However, this working-dir is empty. This is caused by the volume mount in the docker-compose-test.yml with this line:

volumes:
  - .:/var/www/html

In the Dockerfile I also have this:

COPY . /var/www/html/

So when I remove the volume mount in docker-compose-test.yml, all files are there, so the copying does work for the Dockerfile, but not mounting it later on. I saw this thread and tried some of their solutions and tested it with their test script:

variables:
  SHARED_PATH: /builds/shared/$CI_PROJECT_PATH
script:
  - mkdir -p ${SHARED_PATH}
  - touch ${SHARED_PATH}/test_file
  - docker run -v ${SHARED_PATH}:/mnt ubuntu ls /mnt

But this still resulted in an empty /mnt dir, while the test_file should have been there. In the GitLab runner I added this line to the config:

volumes = ["/cache", "/builds:/builds"]

Unfortunately, this did not change anything. I am not sure, but my guess is that I need to access the /builds from my other docker instance, because I have a feeling that I am mounting the /builds from the host machine, which is not the docker I am using in my pipeline. If this is the case, I am not sure how to configure my Kubernetes cluster to use the other one. The weird thing is that when
I do cd /builds/projects/laravel-api (my repo is named laravel-api and its inside the projects group) and then ls in my pipeline, I do see my repository containing all the files. But when I try to mount that directory in my docker-compose-test.yml I still get an empty dir. So I mean this:

volumes:
  - /builds/projects/laravel-api:/var/www/html

So every way of mounting volumes after builds are resulting in empty directories…

Wrap up

So to summarize the problem. Every form of mounting I do in my pipeline results eventually in an empty directory. When copying files from a Dockerfile only the directory does work, but that is not something I can work with.

I hope this covers the entire problem. Some help is really appreciated! If there are any questions about the setup or something like that, please ask I will respond ASAP!

Spring Boot + MySQL Docker Compose: port exposure refused connection

Spring Boot + MySQL + Docker here. I have the following docker-compose.yml:

version: "3.8"

services:
  myappws_mono_db:
    image: mysql:8.0.32
    restart: unless-stopped
    environment:
      - MYSQL_ROOT_PASSWORD=$MAIN_DB_ROOT_PASSWORD
      - MYSQL_DATABASE=$MAIN_DB_DATABASE
      - MYSQL_CHARSET=utf8mb4
      - MYSQL_COLLATION=utf8mb4_0900_ai_ci
      - MYSQL_ENGINE=InnoDB
    ports:
      - $MAIN_DB_PORT:$MAIN_DB_DOCKER_PORT
    volumes:
      - db:/var/lib/mysql
  myappws:
    depends_on:
      - myappws_mono_db
    build: .
    restart: on-failure
    environment:
      - SERVER_PORT=$SERVER_PORT
      - MAIN_DB_HOST=myappws_mono_db
      - MAIN_DB_PORT=$MAIN_DB_DOCKER_PORT
      - MAIN_DB_DATABASE=$MAIN_DB_DATABASE
      - MAIN_DB_USERNAME=$MAIN_DB_USERNAME
      - MAIN_DB_PASSWORD=$MAIN_DB_PASSWORD
    ports:
      - $SERVER_PORT:$WS_DOCKER_PORT
volumes:
  db:

The following .env file:

MAIN_DB_HOST=127.0.0.1
MAIN_DB_PORT=3307
MAIN_DB_DOCKER_PORT=3306
MAIN_DB_USERNAME=root
MAIN_DB_PASSWORD=123456
MAIN_DB_ROOT_PASSWORD=123456
MAIN_DB_DATABASE=myapp_db_local
SERVER_PORT=9200
WS_DOCKER_PORT=9201

The following Dockerfile:

FROM eclipse-temurin:11
MAINTAINER myapp.io

RUN mkdir /opt/app

COPY app/build/libs/myapp-ws.jar myapp-ws.jar

ENTRYPOINT ["java","-jar","myapp-ws.jar"]

When I run ./gradlew clean bootJar && docker-compose --env-file .env up -d both MySQL and Spring Boot containers start up just fine but the Spring Boot API is not available from my host machine via curl:

curl -ik -H "Accept: application/json" -H "Content-Type: application/json" -d '{"name":"ACME, Inc.", "website":"http://example.com"}' -X POST 'http://127.0.0.1:9201/ap1/v1/vendors/'
curl: (7) Failed to connect to 127.0.0.1 port 9201: Connection refused

When I try port 9200 (just in case) I get a similar but different error:

curl -ik -H "Accept: application/json" -H "Content-Type: application/json" -d '{"name":"ACME, Inc.", "website":"http://example.com"}' -X POST 'http://127.0.0.1:9200/ap1/v1/vendors/'
curl: (52) Empty reply from server

So clearly the Spring Boot container is not exposing its port to my host machine, but for the life of me, I’m not sure how/where to change what!?

Python AWS Lambda in error because of pyjwt[crypto] (cryptography)

I have the following error when i run my AWS lambda under python 3.9 :

[ERROR] Runtime.ImportModuleError: Unable to import module 'lambda_function': /lib64/libc.so.6: version `GLIBC_2.28' not found (required by /var/task/cryptography/hazmat/bindings/_rust.abi3.so)
Traceback (most recent call last):

I am aware that this is somehow a compilation issue so here the steps i have done until the AWS lambda deployment :

  • Create a Dockerfile :
# syntax=docker/dockerfile:1
FROM ubuntu:latest
ENV TZ=Europe/Paris
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

RUN apt-get update -y
RUN apt-get install software-properties-common -y
RUN add-apt-repository ppa:deadsnakes/ppa
# Install py39 from deadsnakes repository
RUN apt-get install python3.9 -y
# Install pip from standard ubuntu packages
RUN apt-get install python3-pip -y
RUN apt-get install zip -y

RUN apt-get install libc6 -y

RUN mkdir /home/packages

RUN pip install --target=/home/packages pyjwt[crypto]==2.6.0 
RUN pip install --target=/home/packages pymongo[srv]==4.3.3
  • Inside the docker container, i do : cd /home/packages
  • Then : zip -r ../package.zip .
  • Then i use docker cp to copy the package.zip to my MacOS host.

I use zip -g package.zip lambda_function.py and i upload the .zip file using boto3.

enter image description here

I would like to know why this is not enough or what am i missing here ?

Note : i need to keep using the zip method to upload the lambda package for other reasons, unless there is no other choice of course..

EDIT : In response to @Tom ‘s answer if i add the mentioned pip command in my Dockerfile :

 > [12/14] RUN pip install --platform --platform manylinux2014_x86_64 --implementation cp --python 3.9 --only-binary=:all: --upgrade --target /home/packages cryptography:                                                      
#19 3.185 ERROR: Could not find a version that satisfies the requirement manylinux2014_x86_64 (from versions: none)
#19 3.186 ERROR: No matching distribution found for manylinux2014_x86_64

How to arrange the html file and use all the other css and javascript files?

The whole project can be found here, I added it to GitHub:

https://github.com/chocolade1972/Google-Maps-Api-Development

For making it easier to see and find visually I created for each part a folder and put it’s files inside.

folders

in each folder: Load Bar , Map, Range Slider there is two files: css and js

this is the index.html content

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Maps Api</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <link href="Map/map.css" rel="stylesheet">
    <link href="Load Bar/loadbar.css" rel="stylesheet">
</head>

<body style="background-color:#0d0f07;">

  

<style type="text/css">
    body {
        overflow: hidden;
    }
</style>

</body>

<script src="Map/map.js" type="text/javascript"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="Load Bar/loadbar.js" type="text/javascript"></script>
<div class='progress' id="progress_div">
  <div class="center-screen">
  <h1 id="loading-message">...טוען מפה</h1>
   <div class='bar' id='bar1'></div>
   <div class='percent' id='percent1'></div>
  </div>
</div>

<input type="hidden" id="progress_width" value="0">
<div class="range-slider">
  <input class="input-range" type="range" value="50" min="1" max="100">
  <span class="range-value"></span>
</div> 
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="Range Slider/rangeslider.js" type="text/javascript"></script>

</html>

the Load Bar and the Range Slider are executing fine, but the map is never loading.

this is the map css content file:

#map
    {
        width: 1600px;
        height:850px;
        margin: 0;
        position: absolute;
        top: 48%;
        left: 50%;
        margin-right: -50%;
        transform: translate(-50%, -50%)
    }
    
    #map.fullscreen {
        position: fixed;
        width:100%;
        height: 100%;
      }

and them ap content of the javascript file:

src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap&v=weekly&language=he"

    function initMap() {
        // The location of Uluru
        const uluru = { lat: 32.1582615544072, lng: 34.89155037133181 };
        // The map, centered at Uluru
        map = new google.maps.Map(document.getElementById("map"), {
          zoom: 11,
          center: uluru,
          disableDefaultUI: true,
          fullscreenControl: true,
          
          options: {
    gestureHandling: 'greedy'
  }
        });
    
        const rectangle = new google.maps.Rectangle({
            strokeColor: "#FF0000",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#FF0000",
            fillOpacity: 0.35,
            map,
            bounds: {
                north: uluru.lat - 0.005,
                south: uluru.lat + 0.005,
                west: uluru.lng - 0.005,
                east: uluru.lng + 0.005,
            },
          });
      
} 
      window.initMap = initMap;

I want to rebuild my Stencil.js project from a build

I wanted to deployment my stencil project in server, using “WWW” output, but I have some problems, for that I tried to use some propertys in this doc:

https://stenciljs.com/docs/www

My project was erased and I only have the build.

I wasn’t understand the “DIR” property (I don’t now what is a: “web distribution directory”), for that i added the next code In the “stencil.config.ts” file.

dir: ".", 

The result:

import { Config } from '@stencil/core';
export const config: Config = {
  namespace: 'cosmo',
  outputTargets: [
    {
      type: 'dist',
      esmLoaderPath: '../loader',
    },
    {
      type: 'dist-custom-elements',
    },
    {
      type: 'docs-readme',
    },
    {
      type: 'www',
      dir: ".",
      serviceWorker: null, // disable service workers
    },
  ],
};

When I put the command “npm run build” in the terminal, all my project was erased, including the “.git” archives, but the image in the “assets” folder were not deleted. I can’t recovery the proyect, but I have the “build”. for that I wanted to recovery my project using the build.

My erased project, only have the folders, all is empty

¿I can rebuild my project using the build? (I’m not desperate, I was just starting out, I could rebuild everything in one day)

Build

Angular: Data Table – Sort letters and numbers in columns with angular material mat-sort

I have a problem sorting my columns with angular material mat-sort.

I have some codes called correlative_request which were assigned with letters, numbers and characters. Here the problem is that when I try to sort my table in ascending order I would expect it to start counting in the following way

B-23-3-01
B-23-3-02
B-23-3-03
….
B-23-3-029

But instead of doing it like this, it does it by taking the minors and then the majors something like this:

B-23-3-01
B-23-3-010
B-23-3-011
….
B-23-3-02
B-23-3-020
….
B-23-3-029

I made a small demo of how I have it in my project, to replicate my error, in my project I use component inheritance to pass the dataSource to my table but that does not interfere with the sort itself. Demo In Stackblitz

If someone helps me I would be grateful, I leave you some images of what the jump of the numbers looks like when I try to order them

enter image description here

Issue with react linking using react-router-dom

Im trying to make a basic recipe app, with a home page that shows all the recipes. I want to be able to click on the recipes and display a new page, with data specific to that recipe showing. For some reason my links won’t work, I don’t even get the option to click on the image.
If it’s easier, here is the github link to my project: https://github.com/hannahwardnz01/React-recipe-app

App.js

import Pages from "./pages/Pages";
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import styled from "styled-components";
import Search from "./components/Search";
import { GiHotMeal } from "react-icons/gi";

function App() {
  
  return (
    <div className="App">
      <Router>
        <Header>
          <Nav>
            <GiHotMeal /> 
              <Logo to="/">
                <h3>Recipe finder</h3>
              </Logo>
          </Nav>
          <Search />
        </Header>
        <Pages />
      </Router>
    </div>
  );
}

const Logo = styled(Link)`
  text-decoration: none;
  font-size: 1.5rem;
  font-family: "Consolas", sans-serif;
  padding-left: 1rem;
`;

const Nav = styled.div`
  display: flex;
  justify-content: flex-start;
  align-items: center;
  svg {
    color: var(--gray-600);
    font-size: 2rem;
  }
`;

const Header = styled.div`
  padding: 0rem 0rem 0rem 1rem;
  display: flex;
  justify-content: space-between;
`

export default App;

Pages.jsx

import Home from "./Home";

function Pages() {
  return <Home />;
}

export default Pages;

Home.jsx

import Favorite from "../components/Favorite";
import All from "../components/All";

function Home() {
  return (
    <div>
      <Favorite />
      <All />
    </div>
  );
}
export default Home;

Favorite.jsx

import { useEffect, useState } from "react";
import data from "../data";
import styled from "styled-components";
import { Splide, SplideSlide } from "@splidejs/react-splide";
import "@splidejs/splide/dist/css/splide.min.css";
import Recipe from "../pages/Recipe"

function Favorite() {
  const [favorite, setFavorite] = useState([]);

  useEffect(() => {
    getFavorite();
  }, []);

  const getFavorite = async () => {
    const favs = [];
    for (let i = 0; i < data.length; i++) {
      if (data[i].favorite === true) {
        favs.push(data[i]);
      }
    }
    setFavorite(favs);
  };

  return (
    <div>
      <Wrapper>
        <h2>Favorites</h2>
        {favorite.length === 0 ? (
          <h4>Add a recpe to favorites to see it here!</h4>
        ) : (
          <Splide
            options={{
              perPage: 4,
              pagination: false,
              drag: "free",
              gap: "2rem",
            }}
          >
            {favorite.map((recipe) => {
              return (
                <SplideSlide>
                    <Card>
                    <Link to={`/recipe/${recipe.id}`}>
                        <p>{recipe.title}</p>
                        <img src={recipe.imageURL} alt={recipe.title} />
                        <Gradient />
                      </Link>
                    </Card>
                </SplideSlide>
              );
            })}
          </Splide>
        )}
      </Wrapper>
    </div>
  );
}

const Wrapper = styled.div`
  margin: 0.4rem 1rem;
`;

const Card = styled.div`
  min-height: 15rem;
  border-radius: 0.5rem;
  overflow: hidden;
  position: relative;

  img {
    position: absolute;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  p {
    position: absolute;
    z-index: 10;
    left: 50%;
    bottom: 0%;
    transform: translate(-50%, 0);
    color: white;
    width: 100%;
    text-align: center;
    font-weight: 600;
    font-size: 1rem;
    height: 40%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: transparent;
  }
  SplideSlide {
    background-color: transparent;
  }
`;

const Gradient = styled.div`
  z-index: 3;
  position: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.5));
`;
export default Favorite;

All.jsx

import { useEffect, useState } from "react";
import data from "../data";
import styled from "styled-components";
import Box from "@mui/material/Box";
import Grid from "@mui/material/Unstable_Grid2";
import { useNavigate } from "react-router-dom";

function All() {
  const [all, setAll] = useState([]);

  useEffect(() => {
    getAll();
  }, []);

  const getAll = async () => {
    setAll(data);
  };

  let navigate = useNavigate(); 
  const routeChange = () => { 
    console.log("here")
  }

  function handleClick(){
    console.log("here")
  }

  function getGridRecipe(title, imageURL) {
    return (
      <Grid item xs={12} sm={6} md={3}>
        <Card>
        <Link to={`/recipe/${recipe.id}`}>
          <p>{title}</p>
          <img src={imageURL} onClick={handleClick}/>
          <Gradient />
          </Link>
        </Card>
      </Grid>
    );
  }

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Wrapper>
        <h2>All recipes</h2>
        <Grid container spacing={{ xs: 2, md: 4 }}>
          {all.map((recipe) => {
            return getGridRecipe(recipe.title, recipe.imageURL);
          })}
        </Grid>
      </Wrapper>
    </Box>
  );
}

const Wrapper = styled.div`
  margin: 0.4rem 1rem 0.4rem 1rem;
  justify-content: space-between;
  width: 98%;
`;

const Card = styled.div`
  min-width: 10rem;
  min-height: 15rem;
  border-radius: 0.5rem;
  overflow: hidden;
  position: relative;

  img {
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  p {
    position: absolute;
    z-index: 10;
    left: 50%;
    bottom: 0%;
    transform: translate(-50%, 0);
    color: white;
    width: 100%;
    text-align: center;
    font-weight: 600;
    font-size: 1rem;
    height: 40%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: transparent;
  }
`;

const Gradient = styled.div`
  z-index: 3;
  position: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.5));
`;
export default All;

I’ve tried changing things around, but all the examples online seem to be the same as how I’m doing it. If theres a better way to navigate/route my site, please let me know with examples.

Is there a way to center an element horizontally on a page while there is another element to the right?

Any method I use to center the element does not work because the element on the right has a width to it, so the center element is always off center. I attached a picture to hopefully give a better idea of what I’m trying to accomplish.

The element I’m trying to center is an input field, here is the link to my project as well to give a more complete picture: https://weathervc.netlify.app/

header layout

I have tried countless variations of flexbox and grid to achieve this but the input element remains off center. I have also tried to take the element on the right out of flow, which kind of works, but it does not look good as the element stays stationary and will overlap the center element if the screen width is too small. Of course I could add media queries to constantly change the position but it looks ugly. I would like it to appear nice and responsive.

Perhaps this is not possible without taking an element out of flow? Any help is appreciated.