I currently am building a fitness website and am looking to use Mantine UI accordion component which is based off Typescript. I built my react project with javascript. Is there a way to create a .tsx file and call it into my app.js file?
Here's the error I am currently receiving. Am I missing the export on the Accordian code?
Module not found: Error: Can't resolve './components/Faq' in '/Users/rodriguezmedia/Desktop/blended/src'
import { Group, Avatar, Text, Accordion } from '#mantine/core';
import React from 'react';
const charactersList = [
{
image: 'https://img.icons8.com/clouds/256/000000/futurama-bender.png',
label: 'Bender Bending Rodríguez',
description: 'Fascinated with cooking, though has no sense of taste',
content: "Bender Bending Rodríguez, (born September 4, 2996), designated Bending Unit 22, and commonly known as Bender, is a bending unit created by a division of MomCorp in Tijuana, Mexico, and his serial number is 2716057. His mugshot id number is 01473. He is Fry's best friend.",
},
{
image: 'https://img.icons8.com/clouds/256/000000/futurama-mom.png',
label: 'Carol Miller',
description: 'One of the richest people on Earth',
content: "Carol Miller (born January 30, 2880), better known as Mom, is the evil chief executive officer and shareholder of 99.7% of Momcorp, one of the largest industrial conglomerates in the universe and the source of most of Earth's robots. She is also one of the main antagonists of the Futurama series.",
},
{
image: 'https://img.icons8.com/clouds/256/000000/homer-simpson.png',
label: 'Homer Simpson',
description: 'Overweight, lazy, and often ignorant',
content: 'Homer Jay Simpson (born May 12) is the main protagonist and one of the five main characters of The Simpsons series(or show). He is the spouse of Marge Simpson and father of Bart, Lisa and Maggie Simpson.',
},
{
image: 'https://img.icons8.com/clouds/256/000000/spongebob-squarepants.png',
label: 'Spongebob Squarepants',
description: 'Not just a sponge',
content: 'SpongeBob is a childish and joyful sea sponge who lives in a pineapple with his pet snail Gary in the underwater city of Bikini Bottom. He works as a fry cook at the Krusty Krab, a job which he is exceptionally skilled at and enjoys thoroughly. ',
},
]
interface AccordionLabelProps {
label: string;
image: string;
description: string;
}
function AccordionLabel({ label, image, description }: AccordionLabelProps) {
return (
<Group noWrap>
<Avatar src={image} radius="xl" size="lg" />
<div>
<Text>{label}</Text>
<Text size="sm" color="dimmed" weight={400}>
{description}
</Text>
</div>
</Group>
);
}
function Demo() {
const items = charactersList.map((item) => (
<Accordion.Item label={<AccordionLabel {...item} />} key={item.label}>
<Text size="sm">{item.content}</Text>
</Accordion.Item>
));
return (
<Accordion initialItem={-1} iconPosition="right">
{items}
</Accordion>
);
}
Is there a way to create a .tsx file and call it into my app.js file?
No. You need to delete all of the typescript types (interfaces ...etc) and rename the file to .js.
You need a typescript (compiler) to convert the .tsx file into .js. Otherwise you cannot use .tsx files, since browser can only parse js.
Related
I'm applying star rating to my react app.
so I have lists of star components. Once I click on rating it's applying for the all components.
Like I do star rating to first food, then it gets apply for all foods also.
I want to handle each food rating independently.
Can someone tell me where I'm going wrong ?
befor rating
after rating for one food
here is my..
import React, { useCallback, useEffect } from "react";
import "./styles.css";
import { Rating } from 'react-simple-star-rating'
import Star from './Start';
export default function App() {
const [category, setCategory] = React.useState("Indian");
const [rating, setRating] = React.useState(3);
const handleChange = (value) => {
setRating(value);
}
const Food = {
Indian: [
{
name: "Misal Pav",
description:
"Misal pav is a popular Maharashtrian street food of usal (sprouts curry) topped with onions, tomatoes, farsan (fried savory mixture), lemon juice, coriander leaves and served with a side of soft pav (Indian dinner rolls). The sprouts curry is made from moth bean sprouts. This misal recipe is a tasty and filling vegan dish that can be served as breakfast, lunch or brunch.",
rating: 5,
},
{
name: "Vada Pav",
description:
"Vada pav is a savory dinner roll stuffed with fried mashed and spiced potato fritters. It is a popular vegan street food snack eaten in Mumbai and rest of Maharashtra. This dish is full of flavors and various textures!",
rating: 1,
},
{
name: "Masala Dosa",
description:
"Masala Dosa / dosey / dosai is a variation of the popular South Indian dosa which has its origins in Tuluva Udupi cuisine of Karnataka. It is made from rice, lentils, potato, fenugreek, ghee and curry leaves, and served with chutneys and sambar. It is popular in South India.",
rating: 1,
}
],
Chinese: [
{
name: "Noodles",
description:
"Chinese noodles vary widely according to the region of production, ingredients, shape or width, and manner of preparation. Noodles were invented in China, and are an essential ingredient and staple in Chinese cuisine. They are an important part of most regional cuisines within China, and other countries with sizable overseas Chinese populations.",
rating: 2,
},
{
name: "chilly chicken ",
description:
"Chilli chicken is a popular Indo-Chinese dish of chicken of Hakka Chinese heritage. In India, this may include a variety of dry chicken preparations.",
rating: 2,
},
{
name: "Manchurian",
description:
"Veg Manchurian is a tasty Indo Chinese dish of fried veggie balls in a spicy, sweet and tangy sauce. ",
rating: 2,
}
],
Italian: [
{
name: "Pizza",
description:
"Though a slab of flat bread served with oil and spices was around long before the unification Italy, there’s perhaps no dish that is as common or as representative of the country as the humble pizza.",
rating: 3,
},
{
name: "Pasta",
description:
"pasta, any of several starchy food preparations (pasta alimentaria) frequently associated with Italian cuisine and made from semolina, the granular product obtained from the endosperm of a type of wheat called durum, and containing a large proportion of gluten (elastic protein).",
rating: 3,
},
{
name: "Lasagna",
description:
"Lasagna is a wide, flat pasta noodle, usually baked in layers in the oven. Like most Italian dishes, its origins are hotly contested, but we can at least say that’s its stronghold is in the region of Emilia-Romagna, where it transformed from a poor man’s food to a rich meal filled with the ragù, or meat sauce.",
rating: 3,
}
]
};
const handleChangeButton = (cat) => {
setCategory(cat);
};
useEffect(() => {
setCategory(category);
}, [setCategory, category]);
return (
<div className="App">
<h1>
<img
className="logo"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAACWCAMAAAAL34HQAAABelBMVEX////+/v7/tABHIQzqLir/tgDoAAD/uAD/uwDqKyc6AAAAAADqIBv1t7Y0AAApAAD/vwDqJiL73dwtAABEGwDx7+3s6efMxcL59/YjAADb3NwdAADf29nV0M7h4uLpGhTfAADzl5b4xcSQgXtpVFLDvLqGdW9kSDxBFQC1q6cWAACZi4VnNwDFhwBsW1yfk49OKxjkowA2Dgw7FAvuYmD0pqXSAAD86OfsOzj609Pwe3lbTEt8aWNbOy1NMy08CABWQDpMKB9uVktVLADx59eEeXqVWwD/1YKMdVtSOj2lbAD93aD+w1L/y28+Mz92RgD+vTi3egD/7M8rDiJCHx7ZyKxVLxBCLDVPGwBQSFHWkwBxanOGVwqOYABwJwD1kwC2YA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pWuuPeplE+dOHciyhYNAoIRJ6Lbr+WGzvg4gRunv7gdqBstmaLPzIvZvwJduvJKFAUTNQrLrLyFSChFwlpS1J2gWMXsv7aFuV6L5toleS50qUoLec9+DWDH23tCsPsiqJn0ejago6rLHo8aE/lbwWpsUAq0gXRo2g54J78BhuwYNstV9RYoaURv1UXyutSjy9YSzWG/WxMRE+AgiNLTXqVwdQGVAXUCztYiMkDGvGYzGGGFSrnl5LsWHXxMOFRhUYVqUgIEx+Safjfs8blH0WYeZyKKGruIBQylb1FMZGJHCs+T8g4HIVsBNPZn9SFqI333fZ4X3NeUvsQYzmNiIxvV4AES5rDqexN7PLl7uuPePJv03rQLJdw9Pg3aosDhMNTO9WBlyPaq64/UM7eAdu9sxAQ2AfagATUDs9oErTf4IAPboycTs6BNuR6IWYe7xfJu3x6KAzcasZ9GyM3uoNlD+76MLweyIAuacDZTeME3VYiG6RjoyT5R4l4zxraXxmyVLt1R6L7PZtr55RZXn1aCrDszaLEjEfTMWscNtEfDwftMBAzP7pZBsYnrnZ3VKgR76tegyO0t58jcvG/JwPYlMLnULvG+Xxlp+bEIwSY7XXKYOuyvvQlUOfWIHaLWoDcbutwSBCMSTisPwPEkKcrctXmHUH5OdXAjyYAom3b2ijB48vdhwhLHyWsch7UeB3dYdDRJ5P9N4QPTjsUd0Oq7sNBA92glHAtWNTcLfATMZlBwDrSXQXWJZKx8TKB4f2WITeAPkE7K88JHpWLuonZfDIcCvEAuW6E0DCGQ/O+8MQvPqetnoHB4cZ2y/yJ6ZM0nC20kXQYhMJVaTvJo7B9l0JxLRP7N9duCsKEK/+FyJOZgh6WsWTAAAAAElFTkSuQmCC"
alt="Good Food"
/>
Good Food
</h1>
<p>Checkout my Favourite food items here ...</p>
<div className="btn-container">
{Object.keys(Food).map((cat, i) => (
<button
key={i}
className={category === cat ? "active" : ""}
onClick={() => handleChangeButton(cat)}
>
{cat}{" "}
</button>
))}
</div>
<h2>List</h2>
<div className="list-container">
{Food[category].map((foodie, i) => (
<div className="list-item" key={i}>
<Star
count={5}
size={40}
value={rating}
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange} />
<h5>{foodie.description}</h5>
</div>
))}
</div>
</div>
);
}
It's because you are getting Star component's value props from one source which is rating.
You need to have an individual value for each Star components.
Replace your Star component with:
<Star
count={5}
size={40}
value={foodie.rating}
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange}
/>
Edit:
Edit:
You also need to put the Food object inside a useState so you can edit the ratings for each food categories.
ex:
const [food, setFood] = useState({
Indian: [
{
name: "Misal Pav",
description:
"Misal pav is a popular Maharashtrian street food of usal (sprouts curry) topped with onions, tomatoes, farsan (fried savory mixture), lemon juice, coriander leaves and served with a side of soft pav (Indian dinner rolls). The sprouts curry is made from moth bean sprouts. This misal recipe is a tasty and filling vegan dish that can be served as breakfast, lunch or brunch.",
rating: 5,
},
{
name: "Vada Pav",
description:
"Vada pav is a savory dinner roll stuffed with fried mashed and spiced potato fritters. It is a popular vegan street food snack eaten in Mumbai and rest of Maharashtra. This dish is full of flavors and various textures!",
rating: 1,
},
{
name: "Masala Dosa",
description:
"Masala Dosa / dosey / dosai is a variation of the popular South Indian dosa which has its origins in Tuluva Udupi cuisine of Karnataka. It is made from rice, lentils, potato, fenugreek, ghee and curry leaves, and served with chutneys and sambar. It is popular in South India.",
rating: 1,
}
],
...
and to set Rating you can do:
const setRating = (type: string, food: string, rating: number) => {
setFood((prevFood) => {
return {
...prevFood,
[type]: prevFood[type].map((foodData: any) => {
if (foodData.name === food) {
return {
...foodData,
rating
}
}
return foodData;
})
}
})
}
This is happening because you are updating you state rating, and using this state in all your lists.
<Star
count={5}
size={40}
value={rating} // <----- state that get's updated
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange} />
Instead you need to update the FOOD object. One way would be you can code your onChange such that it finds the element for which you selected starts, and based on that it can update the ratings property and then you can use that rating propery in component.
<Star
count={5}
size={40}
value={foodie.rating} <-- since you will update the FOOD object you'll get desired result.
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange} />
You can update rating independently via useState
Here you don't have any unique id so i find name.
key refers to food[key] ,
ob refers which rating has to updated just pass entire object, like food[key][position]
const handleUpdateRating = (key, ob) => {
setFood((prevData) => ({
...prevData ,
[key]:prevData.[key].map((obj) =>
obj.name === ob.name ? {...obj , rating:ob.rating + 1} : obj
)
}))
};
This is the page html where I create the object. Part of description must be bold:
const agencyProps = {
title: "Managed agency selection",
paragraph: "Strengten your onboarding process",
videoImage: {
src: "/img/video.png",
alt: "background",
width: 330,
height: 520,
},
selections: {
cardOne: {
title: "Brief",
bold: "THIS",
description: `Complete brief or simple guidance on what to include, we've got you covered`,
width: "430px",
},
cardTwo: {
title: "Search",
description:
"In-depth agency search covering, criteria matching, door knocking and due-dilligence vetting.",
width: "460px",
},
cardThree: {
title: "Pitch",
description:
"Comprehensive pitch management, including comms, diary management and pitch hosting.",
width: "490px",
},
},
};
This is the component, where I pass the object property:
<StyledCard style={{ maxWidth: `${selections.cardTwo.width}` }}>
<StyledIconWrapper>
<FaSearch size="1x" color="#0f0f0f" />
</StyledIconWrapper>
<StyledTitleDescriptionWrapper>
<StyledSelectTitle>
{selections.cardTwo.title}
</StyledSelectTitle>
<StyledSelectDescription>
{selections.cardTwo.description}
</StyledSelectDescription>
</StyledTitleDescriptionWrapper>
</StyledCard>
I've tried to put in <b></b> the part which I like, tried with making getter and using "this" with property 'bold' but still cant manage to catch the words which i like to be bold.
Hope explanation is ok and thanks in advance!
One way is to wrap the text to be bold in a <strong> tag, e.g.:
cardOne: {
description: "This text is <strong>bold</strong>.",
title: // ...
width: // ...
}
you have to use <strong> <strong/> tag and pass that to dangerouslySetInnerHTML
more information on this page
You can add <strong> or <b> tags around the part of the description you want bolded.
cardOne: {
title: "Brief",
description: `Complete brief or <b>simple guidance</b> on what to include, we've got you covered`,
width: "430px"
};
Then you can render the description with dangerouslySetInnerHTML.
<p dangerouslySetInnerHTML={{ __html: cardOne.description }} />
You can set the description to a React fragment and use the <strong> element to wrap the bold text.
cardTwo: {
title: "Search",
description:
<>In-depth agency search <strong>covering</strong>, criteria matching, door knocking and due-dilligence vetting.</>,
width: "460px",
},
there is also this npm package you can use. you can map through your obj and if the bold attribute is needed replace the text or part of it with your styled text.
https://www.npmjs.com/package/react-string-replace
obj.map(item => (
<YOURLIST>
{reactStringReplace(
item.DESCRIPTION,
item.DESCRIPTION,
match => (
<span style={{fontWeight:bold}}>{match}</span>
)
)}
</YOURLIST>
))
I was following a tutorial on youtube (https://youtu.be/3HNyXCPDQ7Q) for creating a portfolio website. I hosted the website using Netlify, 20 days later when I revisited the website, the website was just a blank screen. When I tested again on localhost, the problem was with sanity. When I connected to sanity, the screen would go blank.
Now the problem is that the regular website content is visible, but the data from sanity is not being fetched to the react app.
I have added some documents in the abouts schema via the sanity gui.
Abouts Schema:
export default {
name: "abouts",
title: "Abouts",
type: "document",
fields: [
{
name: "title",
title: "Title",
type: "string",
},
{
name: "description",
title: "Description",
type: "string",
},
{
name: "imgUrl",
title: "ImgUrl",
type: "image",
options: {
hotspot: true,
},
},
],
};
About.jsx code:
import React, { useState, useEffect } from "react";
import { motion } from "framer-motion";
import "./About.scss";
import { urlFor, client } from "../../Client";
import { AppWrapper } from "../../wrapper/";
const About = () => {
const [abouts, setAbouts] = useState([]);
const querySelector = async () => {
const query = '*[_type == "abouts"]';
const aboutsQuery = await client.fetch(query);
aboutsQuery.then((data) => setAbouts(data));
};
useEffect(() => {
querySelector();
}, []);
return (
<>
<motion.div
className="app__about-header"
whileInView={{ x: [1000, 0] }}
transition={{ duration: 1 }}
viewport={{ once: true }}
>
<h1 className="head-text">
<span>About</span> Me
</h1>
</motion.div>
<motion.div
className="app__about-desc"
whileInView={{ opacity: [0, 1] }}
transition={{ duration: 1 }}
viewport={{ once: true }}
>
<h3 style={{ marginBottom: 10 }}>Who I am?</h3>
<p className="p-text">
Some text here.
</p>
</motion.div>
<motion.div
style={{ marginTop: 40 }}
whileInView={{ x: [-1000, 0] }}
transition={{ duration: 1 }}
viewport={{ once: true }}
>
<h2 className="head-text">
What I <span>Love to do?</span>
</h2>
</motion.div>
<div className="app__profiles">
{abouts.map((about, index) => {
return (
<motion.div
whileInView={{ opacity: [0, 1] }}
whileHover={{ scale: 1.1 }}
transition={{ duration: 1, type: "tween" }}
className="app__profile-item"
key={index}
viewport={{ once: true }}
>
<img src={urlFor(about.imgUrl)} alt={about.title} />
<h2 className="bold-text" style={{ marginTop: 20 }}>
{about.title}
</h2>
<p className="p-text">{about.description}</p>
</motion.div>
);
})}
</div>
</>
);
};
export default AppWrapper(About, "about", "app__whitebg");
This Client.js file will connect to the sanity CMS.
Client.js code:
import SanityClient from "#sanity/client";
import imageUrlBuilder from "#sanity/image-url";
export const client = SanityClient({
projectId: "hard coded value added here",
dataset: "portfoliodataset",
apiVersion: "2022-08-11",
useCdn: true,
token: "token value here",
});
const builder = imageUrlBuilder(client);
export const urlFor = (source) => builder.image(source);
I have tried the env variable as well in client.js file.
for eg. projectId: process.env.REACT_APP_SANITY_PROJECT_ID
and I have tried the hard coded values as well. Both don't seem to work.
Note that I have also added the localhost:3000 and the website url in the CORS origin.
Please help me, I am stuck on this problem for a few days now.
I dont know whether you are struck in this or not but giving you reply in case in future if someone struck at this point they can fix it. I also faced the same issue and strucked for the time being and later I realized the issue. The issue is you can't give some random name to the dataset
export const client = SanityClient({
projectId: "hard coded value added here",
dataset: "portfoliodataset",
apiVersion: "2022-08-11",
useCdn: true,
token: "token value here",
});
Here in this dataset field you have to give the dataset name which is in sanity.json file. Hope it would help you
I was facing same issue and I was able to fix it by doing following stuff:
Installing dotenv node package
Moving .env file to frontend_react folder. (I accidentally created it under src folder)
I hope that it would help you too.
Make sure you have import the key and run the sanity client on your localhost
I had exactly the same problem, in the same tutorial. make sure first you have internet connection, then try restarting everything even with internet on.
Its basically a network issue not withstanding any other possible cause of error, but you could give it time then later refresh the react app as well as the sanity client.
Also you could try adding some more code to give the compiler something new to compile, some how the app will load sanity.
Check your sanity.json or sanity.config.js file (if you are using vite) and make sure the dataset you are using is the correct one. It has to match what you have in the client.js file
I had the same issue
I'm following the tutorial on react.js and I got into this error I don't know what is the main cause behind this error
Thank you to everyone who contributes error:
TypeError: Cannot read property 'map' of undefined
import { Link } from "react-router-dom";
function About(props) {
const leaders = props.leaders.map((leader) => {
return <p>Leader {leader.name}</p>;
});
I'm importing leaders data in the main component
Main component:
import React, { Component } from "react";
import Home from "./HomeComponent";
import Contact from "./ContactComponent";
import About from "./AboutComponent";
import Menu from "./MenuComponents";
import Dishdetail from "./DishdetailComponent";
import Header from "./HeaderComponent";
import Footer from "./FooterComponent";
import { Dishes } from "../shared/dishes";
import { Comments } from "../shared/comments";
import { Leaders } from "../shared/leaders";
import { Promotions } from "../shared/promotions";
import { Switch, Route, Redirect } from "react-router-dom";
class Main extends Component {
constructor(props, context) {
super(props, context);
this.state = {
dishes: Dishes,
comments: Comments,
promotions: Promotions,
leaders: Leaders,
};
}
render() {
const HomePage = () => {
return (
<Home
dish={this.state.dishes.filter((dish) => dish.featured)[0]}
promo={this.state.promotions.filter((promo) => promo.featured)[0]}
leader={this.state.leaders.filter((leader) => leader.featured)[0]}
/>
);
};
const DishWithId = ({ match }) => {
return (
<Dishdetail
dish={this.state.dishes.filter((dish) => dish.id === parseInt(match.params.dishId, 10))[0]}
comments={this.state.comments.filter((comment) => comment.dishId === parseInt(match.params.dishId, 10))[0]}
/>
);
};
return (
<div>
<Header />
<Switch>
<Route path="/home" component={HomePage} />
<Route exact path="/menu" component={() => <Menu dishes={this.state.dishes} />} />
<Route path="/menu/:dishId" component={DishWithId} />
<Route exact path="/contactus" component={Contact} />
<Route exact path="/aboutus" component={About} />
<Redirect to="/home" />
</Switch>
<Footer />
</div>
);
}
}
export default Main;
The leader's file:
export const Leaders = [
{
id: 0,
name: "Peter Pan",
image: "/assets/images/alberto.png",
designation: "Chief Epicurious Officer",
abbr: "CEO",
featured: false,
description:
"Our CEO, Peter, credits his hardworking East Asian immigrant parents who undertook the arduous journey to the shores of America intending to give their children the best future. His mother's wizardry in the kitchen whipping up the tastiest dishes with whatever is available inexpensively at the supermarket, was his first inspiration to create the fusion cuisines for which The Frying Pan became well known. He brings his zeal for fusion cuisines to this restaurant, pioneering cross-cultural culinary connections.",
},
{
id: 1,
name: "Dhanasekaran Witherspoon",
image: "/assets/images/alberto.png",
designation: "Chief Food Officer",
abbr: "CFO",
featured: false,
description:
"Our CFO, Danny, as he is affectionately referred to by his colleagues, comes from a long-established family tradition in farming and produce. His experiences growing up on a farm in the Australian outback gave him a great appreciation for varieties of food sources. As he puts it in his own words, Everything that runs wins, and everything that stays, pay!",
},
{
id: 2,
name: "Agumbe Tang",
image: "/assets/images/alberto.png",
designation: "Chief Taste Officer",
abbr: "CTO",
featured: false,
description:
"Blessed with the most discerning gustatory sense, Agumbe, our CFO, personally ensures that every dish that we serve meets his exacting tastes. Our chefs dread the tongue lashing that ensues if their dish does not meet his exacting standards. He lives by his motto, You click only if you survive my lick.",
},
{
id: 3,
name: "Alberto Somayya",
image: "/assets/images/alberto.png",
designation: "Executive Chef",
abbr: "EC",
featured: true,
description:
"Award-winning three-star Michelin chef with wide International experience having worked closely with whos-who in the culinary world, he specializes in creating mouthwatering Indo-Italian fusion experiences. He says, Put together the cuisines from the two craziest cultures, and you get a winning hit! Amma Mia!",
},
];
This community is great
You are trying to iterate trough props.leaders which is undefined, it has to be array. In your scenario it seems there is a missing attribute and that's causing this issue.
Need to pass leaders to props in that <Route /> component as:
<Route exact path="/aboutus" component={<About leaders={this.state.leaders} />} />
I need to import images(several) from my image file dynamically by a map method. First, I want to set a base URL to my images file and then read the image's name from my JSON file which includes the image property and then set the image src accordingly.
The JSON file is like below :
{
"title": "Blue Stripe Stoneware Plate",
"brand": "Kiriko",
"price": 40,
"description": "Lorem ipsum dolor sit amet...",
"image": "blue-stripe-stoneware-plate.jpg"
},
{
"title": "Hand Painted Blue Flat Dish",
"brand": "Kiriko",
"price": 28,
"description": "Lorem ipsum dolor sit amet...",
"image": "hand-painted-blue-flat-dish.jpg"
},
my images folder :
I have read the products by redux which is works perfectly =>
const products = this.props.products;
console.log(products, 'from redux');
const fetchProducts = [];
for (let key in products) {
fetchProducts.push({
...products[key]
});
}
the console.log() =>
Now I want to define a base URL like this which later use as image src by adding the image's name from the JSON file in the map method :
const baseUrl = '../../components/assets/images/';
const fetchProducts = [];
for (let key in products) {
fetchProducts.push({
...products[key]
});
}
const productCategory = fetchProducts.map((product, index) => {
return (
<Photo
key={index}
title={product.title}
brand={product.brand}
description={product.description}
imageSource={baseUrl + product.image}
imageAlt={product.title}
/>
);
});
my Photo component looks like below :
const photo = props => (
<div className={classes.Column}>
<img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />
<div className={classes.Container}>
<p>{props.brand}</p>
<p>{props.title}</p>
<p>{props.price}</p>
</div>
</div>
);
export default photo;
unfortunately, I have faced this error:
Thanks in advance and sorry for my bad English :)
Import is not working like that. You can use a base URL like that:
const baseUrl = "../../components/assets/images/";
Then you can pass to your Photo component like that:
<Photo
key={index} // Don't use index as a key! Find some unique value.
title={product.title}
brand={product.brand}
description={product.description}
imageSource={baseUrl + product.image}
imageAlt={pro.title}
/>;
Lastly, in your Photo component use require:
<img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />
or like that:
<img src={require( "" + props.src )} alt={props.imageAlt} />
But, don't skip "" part or don't use it directly like:
<img width="100" alt="foo" src={require( props.src )} />
since require wants an absolute path string and first two do this trick.
Try this solution for dynamic image:-
**Componet**
const photo = props => (
<div className={classes.Column}>
<img src={require( `../../components/assets/images/${props.imageSource}`)} alt={props.imageAlt} />
<div className={classes.Container}>
<p>{props.brand}</p>
<p>{props.title}</p>
<p>{props.price}</p>
</div>
</div>
);
**Include Componet**
const productCategory = fetchProducts.map((product, index) => {
return (
<Photo
key={index}
title={product.title}
brand={product.brand}
description={product.description}
imageSource={product.image}
imageAlt={product.title}
/>
);
});
So here is what I found and it worked for me.
"file-loader": "4.3.0"
React: 16.12
Run this in your terminal:
npm run eject
Check file-loader in config/webpack.config and located file-loader configurations. What I did was, I created a directory called static/media/{your_image_name.ext} following the notation there:
options: {
name: "static/media/[name].[hash:8].[ext]"
}
and then imported this image like
import InstanceName from "static/media/my_logo.png";
Happy Hacking!
After trying all kinds of solutions, including backticks <img src={require( `${ props.imageSource }` )} and others, nothing was working. I kept getting the error Cannot find module, even though my relative paths were all correct. The only primitive solution I found, if you have a relatively small number of possible images, is to predefine a Map that will map to the actual imports. (Of course this won't work for lots of images.)
import laptopHouse from '../../images/icons/laptop-house.svg'
import contractSearch from '../../images/icons/file-contract-search.svg'
..
const [iconMap, setIconMap] = useState({
'laptopHouse': laptopHouse,
'contractSearch': contractSearch,
..
});
..
<img src={iconMap[props.icon]} />
i solved this typescript issue as follows in my project.
hope this is helpful
export const countryData = {
'sl': { name: 'Sri Lanka', flag: '/flag-of-Sri-Lanka.png' },
'uk': { name: 'UK', flag: '/flag-of-United-Kingdom.png' },
'usa': { name: 'USA', flag: '/flag-of-United-States-of-America.png' },
'ca': { name: 'Canada', flag: '/flag-of-Canada.png' },
'It': { name: 'Italy', flag: '/flag-of-Italy.png' },
'aus': { name: 'Australia', flag: '/flag-of-Australia.png' },
'me': { name: 'Middle East', flag: '/flag-of-Middle-East.png' },
'other': { name: 'Other', flag: '/flag-of-World.png' }, };
"part of URL within Double quotes" + dynamic_URL_via_var combo worked for me.
<Avatar src={require('../assets'+countryData['uk']['flag'])} />
//json data.
"ProductSlider":[
{
"image":"Product1.jpg"
},
{
"image":"Product2.jpg"
}]
//mapping data list in parent component.
{sliderData.map((data) => (
<SwiperSlide className='w-10 '>
<ProductCard data={{imgSrc: data.image}} />
</SwiperSlide>
))}
//child component(linked image).
import React from 'react'
import { CardImg } from 'react-bootstrap'
export default function ProductCard(props) {
let {imgSrc} = props.data;
return (
<div className="overflow-hidden">
<div className='overflow-hidden bg-grey opacity-card' >
<CardImg
variant='top'
src={require(`../assets/images/${imgSrc}`)}
/>
</div>
<div className='text-center p-1 opacity-card-title' >
<div>Add to cart</div>
</div>
</div>
)
}
Even I got the same error
{gallery.map((ch, index) => {....
cannot find module '/../..................png'
I went wrong here, I used src instead of ch
Error
<Image src={src.image} />
Solved
<Image src={ch.image} />