why aren't images loading in preview? - javascript

I am using react.js and the problem that I am having is that the images wont load in npm run preview even though I included them in the public folder, reconfigured the image paths, and they are included in the assets folder in the dist folder. all of the images are showing on the local preview of the website
This is how it looks like
these are my paths for my images in the assets folder
export default [
{
title: "Flaco Ramirez Boxing Website",
imgUrl: "/assets/frb.png",
stack: ["Typescript", "React", "Tailwind", "Vite"],
link: "",
},
{
title: "Portfolio Website ",
imgUrl: "/assets/portfolio.jpeg",
stack: ["Javascript", "React", "Tailwind", "Vite"],
link: "",
},
{
title: "Discord Bot ",
imgUrl: "/assets/discord.png",
stack: ["Python", "Discord.py"],
link: "",
},
];
in PortfolioItem.jsx
import React from 'react';
export function PortfolioItem({ title, imgUrl, stack, link }) {
return (
<a
href={link}
target="_blank"
rel="noopener noreferrer"
className="border-2 border-stone-900 dark:border-white rounded-md overflow-hidden"
>
<img
src={imgUrl}
alt="portfolio"
className="w-full h-36 md:h-48 object-cover cursor-pointer"
/>
<div className="w-full p-4">
<h3 className="text-lg md:text-xl dark:text-white mb-2 md:mb-3 font-semibold ">{title}</h3>
<p className="flex flex-wrap gap-2 flex-row items-center justify-start text-xs md:text-sm dark:text-white ">
{stack.map(item => (
<span className="inline-block px-2 py-1 font-semibold border-2 border-stone-900 dark:border-white rounded-md">
{item}
</span>
))}
</p>
</div>
</a>
)
}
export default PortfolioItem;
in Portfolio.jsx
import React from "react";
import porfolio from "../data/porfolio";
import PortfolioItem from "./PortfolioItem";
export function Portfolio() {
return (
<div className="flex flex-col md:flex-row items-center justify-center">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{porfolio.map((project) => (
<PortfolioItem
imgUrl={project.imgUrl}
title={project.title}
stack={project.stack}
link={project.link}
/>
))}
</div>
</div>
);
}
export default Portfolio;

Vite's preview task doesn't run a new build. It just serves the dist folder as-is.
If you want to always see the latest build via preview, I suggest you add a pre-script in package.json...
"scripts": {
...
👉 "prepreview": "npm run build", 👈
"preview": "vite preview"
},

Related

How to map an array inside JSON object using typescript?

I'm trying to get an array from a JSON object and then, map it in order to get the data.
Here is the data returned from an API:
{
project: [
{
_createdAt: '2022-12-15T16:45:57Z',
_id: 'cb39338d-4e6d-4c28-9a79-499afca392e6',
_rev: '974wCYB6EQ3xW9LGNZhQvU',
_type: 'project',
_updatedAt: '2022-12-27T04:55:54Z',
image: [Object],
linkToBuild: 'https://github.com/Arotiana137-51/charitty_to_portfolio_jsp',
summary: "This is a project I've done for learning purpose at the University. I've learned the basics of web programing with Java Server Pages ,Servelet ,....", technologies: [Array],
title: 'Charity '
}
]
}
And I wish to map this array in order to get elements from it inside this JSX element :
import React from "react";
import {motion} from 'framer-motion';
import { Project } from "../typing";
import { urlFor } from "../sanity";
type Props = {
projects:Project[];
};
function Projects({projects}: Props) {
console.log(projects);
return (
<motion.div
initial={{opacity:0}}
whileInView={{opacity:1}}
transition={{duration:1.5}}
className="h-screen relative flex overflow-hidden flex-col text-left md:flex-row max-w-full justify-evenly mx-auto items-center z-0">
<h3 className="absolute top-24 uppercase tracking-widest text-teal-400 text-2xl ">
Projects
</h3>
<div className="relative w-full flex overflow-x-scroll overflow-y-hidden snap-x snap-mandatory z-20">
{/*----------- HERE I TRY TO ACCESS THE ARRAY AND MAP IT DIRECTLY, LIKE IN JS-----------------------------------*/}
{ projects.project.map((project,i) => (
<div className="w-screen flex-shrink-0 snap-center flex flex-col space-y-5 items-center justify-center p-20 md:p-44 h-screen">
<motion.img
initial ={{
y: -300,
opacity:0
}}
transition={{duration: 1.2}}
whileInView = {{opacity:1 , y:0 }}
viewport={{ once: true}}
src={urlFor(project.image).url()}
alt="#"/>
<div className=" space-y-10 px-0 md:px-10 max-w-6xl ">
<h4 className="text-4xl font-semibold text-center">
Case study {i+1} of{projects.length}: <span className="underline decoration-teal-700"> {project?.title}</span>
</h4>
<div className="flex items-center space-x-2 justify-center">
{
project?.technologies.map((technology)=>(
<img
className="h-10 w-10"
key={technology._id}
src={urlFor(technology?.image).url()}
alt=""
/>
))
}
</div>
<p>{project?.summary}</p>
</div>
</div>
))}
</div>
<div className="w-full absolute top-[30%] bg-teal-800 left-0 h-[500px] -skew-y-12">
</div>
</motion.div>
);
}
export default Projects;
This normally works on js but my compiler return:
Server Error
TypeError: Cannot read properties of undefined (reading 'map')
because it still considers the prop as an object, even if I try to access the array at the code above, how can i solve it?
You are trying to do project?.technologies.map, but as i see at the JSON above , there is simply no "technologies" key.

Fixed Left- 0 (TailwindCss) overlaping body content

i have an issue on my project i'am working on, i have a SIDEBAR and a TOPHEADER(NAVBAR).., now the issue starts when i want to have a FIXED SIDEBAR without it obscuring other page elements like TopHeader/Navbar and body content to the left side of the page.. tried adding ml-20 on topHeader div but that didnt help as it just opens up a whitespace on the left,,also tried using Space-x-20 class that also didnt help because it only pushed the body content to the right just like iwanted but theres another issue , the TopHeader is stuck on the left ..on this project iam using Tailwindcss to style the project would appreciate the help.
This is how it looks like with the "Fixed left-0 "
enter image description here
enter image description here
How I want it to look: enter image description here
enter image description here
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { HiMenuAlt3 } from "react-icons/hi";
import { AiFillHome, AiOutlinePoweroff } from "react-icons/ai";
import { FiPlay } from "react-icons/fi";
import {
BsDisplay,
BsQuestionCircle,
BsTrophy,
BsTwitter,
} from "react-icons/bs";
import { MdOutlineGames } from "react-icons/md";
import { SiDiscord } from "react-icons/si";
import { BiNews } from "react-icons/bi";
import { TopHeader } from "../../components/TopHeader";
export const Sidebar = ({ children }) => {
const menus = [
{ name: "Home", link: "/", icon: AiFillHome },
{ name: "Play", link: "/", icon: FiPlay },
{ name: "Watch", link: "/", icon: BsDisplay },
{ name: "Leaderboard", link: "/", icon: BsTrophy, margin: true },
{ name: "Games", link: "/", icon: MdOutlineGames },
{ name: "News", link: "/", icon: BiNews },
{ name: "F.a.q", link: "/", icon: BsQuestionCircle, margin: true },
{ name: "Logout", link: "/", icon: AiOutlinePoweroff },
{ name: "Discord", link: "/", icon: SiDiscord, margin: true },
{ name: "Twitter", link: "/", icon: BsTwitter },
];
const [open, setOpen] = useState(true);
return (
<section className="flex">
<div
className={`fixed left-0 bg-black min-h-screen ${
open ? "w-72" : "w-16"
} duration-500 text-white px-4`}
>
<div className="py-3 flex justify-end">
<HiMenuAlt3
size={26}
className="cursor-pointer"
onClick={() => setOpen(!open)}
/>
</div>
<div className="mt-4 flex flex-col gap-4 relative">
{menus?.map((menu, i) => (
<Link
to={menu?.link}
key={i}
className={`${
menu?.margin && "mt-5"
} flex items-center text-sm gap-3.5 font-medium p-2 hover:bg-indigo-600 rounded-md`}
>
<div>{React.createElement(menu?.icon, { size: "20" })}</div>
<h2
style={{
transitionDelay: `${i + 3}00ms`,
}}
className={`whitespace-pre duration-500 ${
!open && "opacity-0 translate-x-28 overflow-hidden"
}`}
>
{menu?.name}
</h2>
</Link>
))}
</div>
</div>
<div className="bg-gray-800 w-full p-3">
<>
<TopHeader />
{children}
</>
</div>
</section>
);
};
import React from "react";
import { AiOutlineSearch } from "react-icons/ai";
import { BiUserCircle } from "react-icons/bi";
import { HiOutlineFlag } from "react-icons/hi";
import { IoMdNotificationsOutline } from "react-icons/io";
import "tw-elements";
export const TopHeader = () => {
return (
<div className="max-w-auto mx-auto px-4 mb-5 bg-black text-white">
<div className=" flex justify-between">
<div className="flex space-x-52">
{/*Logo*/}
<div>
<h1 className="flex items-center py-4 px-2 font-semibold">LOGO</h1>
</div>
{/* Search Input */}
<div className="hidden md:flex items-center space-x-1">
<div className="bg-gray-300 text-white rounded-full flex items-center px-2">
<AiOutlineSearch size={20} />
<input
className="bg-gray-300 p-2 rounded-full focus:outline-none"
type="text"
placeholder="Search Games"
/>
</div>
</div>
<div className="flex items-center space-x-3">
{/* Notification Button */}
{/*<button className="py-2 px-2 text-white">
<IoMdNotificationsOutline size={30} />
</button> */}
{/* RightSidebar Button */}
<button className="py-2 px-2 text-white">
<HiOutlineFlag size={30} />
</button>
{/* User Button*/}
<button className="py-2 px-2 text-white">
<BiUserCircle size={30} />
</button>
</div>
</div>
</div>
</div>
);
};
i finally found a good fix for my issue i had above , instead of using tailwind default " fixed left-0 " , i ended up using StickyNode and it kind of solved every bit of problems i had by wrapping my sidebar with stickynode component like this:
<Sticky>
<Sidebar />
</Sticky>

404 when visiting page with dynamic route Gatsby

I'm trying to implement dynamic routing on a Gatsby site - I'm fetching launch data from the SpaceXAPI and creating a new page if a launch contains details. These details pages load correctly when you click on the 'View Details' link to view them from the homepage. When you access the page directly by its url, the page information is not found, resulting in a 404.
Why won't pages with this route load on their own? I'm also looking into ways to persist the state that I'm currently passing in to <Link>.
Repository: https://github.com/nikkipeel/gatsby-spacex
I'm not using <Router> or the createPages API...this is my project structure:
Accessing state through location on the page:
[name].js:
import * as React from 'react'
import moment from 'moment'
import Seo from '../../components/seo'
import ScrollToTop from '../../components/scrollToTop'
import Footer from '../../components/footer'
import '../../styles/tailwind.css'
const Launch = ({ location, name }) => (
<>
<main className="h-screen w-full bg-gray-900 text-white mx-auto">
<Seo title={name} />
{name && (
<>
<div className="flex flex-col md:w-3/4 lg:w-1/2 p-12 mx-auto text-base" key={name}>
<h1 className="mission-name tracking-wide font-bold text-2xl my-4">{name}</h1>
<strong className="tracking-wide text-xl my-2">Flight # {location.state.flight_number}</strong>
<div className="flex items-center my-2">
<strong className="text-xl mr-2">Mission: </strong>
<p className="text-base">{location.state.name}</p>
</div>
<div className="flex items-center my-2">
<strong className="text-xl mr-2">Launch Date: </strong>
<p>{moment(location.state.date_local).format('dddd, MMMM Do YYYY, h:mm:ss a')}</p>
</div>
{location.state.details && <p className="my-2">{location.state.details}</p>}
<a
href={location.state.links.wikipedia}
className="my-2 font-bold font-mono bg-clip-text text-transparent bg-gradient-to-t from-blue-500 via-blue-400 to-blue-300 transition duration-500 ease-in-out hover:text-blue-300 hover:underline pr-8"
>
Learn More
</a>
{location.state.links.video_link && (
<a
href={location.statelinks.video_link}
className="my-2 font-bold font-mono bg-clip-text text-transparent bg-gradient-to-t from-blue-500 via-blue-400 to-blue-300 transition duration-500 ease-in-out hover:text-blue-300 hover:underline p-2"
>
View Launch
</a>
)}
</div>
</>
)}
</main>
<ScrollToTop showBelow={250}></ScrollToTop>
<Footer></Footer>
</>
)
export default Launch
Setting state in <Link> in pastLaunches.js:
<Link
to={`/launches/${name}`}
state={{
name: name,
flight_number: flight_number,
date_local: date_local,
links: links,
rocket: rocket,
details: details
}}
className="mt-4 font-bold font-mono bg-clip-text text-transparent bg-gradient-to-t from-blue-500 via-blue-400 to-blue-300 transition duration-500 ease-in-out hover:text-blue-300 hover:underline w-48"
>
View Details
</Link>
Gatsby collection routes: https://www.gatsbyjs.com/docs/reference/routing/file-system-route-api/
Gatsby example client-only paths: https://github.com/gatsbyjs/gatsby/tree/master/examples/client-only-paths
Netlify issue with Gatsby and 404 pages: https://answers.netlify.com/t/gatsby-4-runtime-importmoduleerror-on-404-pages/46608

3rd party Images gets broken in nextjs production environment

Images that get a response from API are showing broken on production env of next.js.
Here is my code
import Image from 'next/image';
//import PlaceHolderImage from "../public/images/placeholder.png";
interface IProps {
soldDate?: string;
price: string;
address: string;
bed: number;
bath: number;
cars: number;
sqm?: number | null;
image: any;
}
const PropertyCardInfo = (props: IProps): JSX.Element => {
return (
<div className="h-auto text-cpBlack border border-cpGreyLine mb-4">
<div className="w-full h-auto relative">
<Image
src={props.image}
alt={props.address}
width={360}
height={238}
layout="responsive"
/>
</div>
<div className="h-auto flex flex-col justify-between mt-1.5">
<div className="flex items-center justify-between pt-3.5 px-3.5">
<p className="font-semibold">{props.price}</p>
{props.soldDate && <p className="text-cpGrey text-sm">Sold {props.soldDate}</p>}
</div>
<a href="#" className="my-2 px-3.5 text-sm hover:text-cpOrange">
{props.address}
</a>
<div className="pb-3.5 px-3.5 flex text-sm font-semibold">
<p className="mr-2">
{props.bed}
<span className="ml-0.5">bed</span>
</p>
<p className="mr-2">
{props.bath}
<span className="ml-0.5">bath</span>
</p>
<p className="mr-2">
{props.cars}
<span className="ml-0.5">cars</span>
</p>
{props.sqm && (
<p className="mr-2">
{props.sqm}
<span className="ml-0.5">sqm</span>
</p>
)}
</div>
</div>
</div>
);
};
export default PropertyCardInfo;
I have whitelisted the domain and image URL domain in the next.config.js.
It also works well in development and local build environment.
But on deployment to UAT env, it show broken link and show the below error.
But if I pass same image through custom loader function then it worked.
const ImgLoader = ({ src }) => {
return props.image;
};
<Image
loader={ImgLoader}
src={props.image}
alt={props.address}
width={360}
height={238}
layout="responsive"
/>
Do I need to use custom loader for 3rd party images or Do I need to install sharp plugin ?
Please correct me if I am wrong.

tailwind style not applying in next js when using official cli to generate project

I am following the tailwind doc to generate nextJs app.
npx create-next-app -e with-tailwindcss .
Then I've created NavBar component by copying the code of tailwind doc
NavBar.js
import React from "react";
function NavBar() {
return (
<nav className="flex items-center justify-between flex-wrap bg-teal-500 p-6">
<div className="flex items-center flex-shrink-0 text-white mr-6">
<svg
className="fill-current h-8 w-8 mr-2"
width="54"
height="54"
viewBox="0 0 54 54"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M13.5 22.1c1.8-7.2 6.3-10.8 13.5-10.8 10.8 0 12.15 8.1 17.55 9.45 3.6.9 6.75-.45 9.45-4.05-1.8 7.2-6.3 10.8-13.5 10.8-10.8 0-12.15-8.1-17.55-9.45-3.6-.9-6.75.45-9.45 4.05zM0 38.3c1.8-7.2 6.3-10.8 13.5-10.8 10.8 0 12.15 8.1 17.55 9.45 3.6.9 6.75-.45 9.45-4.05-1.8 7.2-6.3 10.8-13.5 10.8-10.8 0-12.15-8.1-17.55-9.45-3.6-.9-6.75.45-9.45 4.05z" />
</svg>
<span className="font-semibold text-xl tracking-tight">Tailwind CSS</span>
</div>
<div className="block lg:hidden">
<button className="flex items-center px-3 py-2 border rounded text-teal-200 border-teal-400 hover:text-white hover:border-white">
<svg
className="fill-current h-3 w-3"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<title>Menu</title>
<path d="M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z" />
</svg>
</button>
</div>
<div className="w-full block flex-grow lg:flex lg:items-center lg:w-auto">
<div className="text-sm lg:flex-grow">
<a
href="#responsive-header"
className="block mt-4 lg:inline-block lg:mt-0 text-teal-200 hover:text-white mr-4"
>
Docs
</a>
<a
href="#responsive-header"
className="block mt-4 lg:inline-block lg:mt-0 text-teal-200 hover:text-white mr-4"
>
Examples
</a>
<a
href="#responsive-header"
className="block mt-4 lg:inline-block lg:mt-0 text-teal-200 hover:text-white"
>
Blog
</a>
</div>
<div>
<a
href="#"
className="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-teal-500 hover:bg-white mt-4 lg:mt-0"
>
Download
</a>
</div>
</div>
</nav>
);
}
export default NavBar;
The appearance of NavBar is not same as the doc
This is what the NavBar should look like:
tailwind.config.js
module.exports = {
mode: 'jit',
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
postcss.config.js
// If you want to use other PostCSS plugins, see the following:
// https://tailwindcss.com/docs/using-with-preprocessors
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
_app.js
import Layout from "../components/Layout";
import "tailwindcss/tailwind.css";
function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
export default MyApp;
Layout.js
import React from 'react';
import NavBar from '../components/NavBar';
function Layout({children}) {
return (
<>
<NavBar/>
<div>
<main>
{children}
</main>
</div>
</>
)
}
export default Layout
The problem is caused by the teal not being associated with a color so adding theme: { colors: require('tailwindcss/colors') } to tailwind.config.js fixes it.
module.exports = {
theme: {
colors: require('tailwindcss/colors'),
},
}

Categories