i'm trying to do a CardList items from a local data.json file using React.Js.
To load the data i'm using a map function:
const ItemsList = data.map(item=>{
return(
<li><img key={item.id} src={"assets/images/sampleImages/" + item.image}/></li>
)
})
Code - PasteBin
but i cannot get the image. No error, just a broken image icon appear.
I've try:
This solution And with URL works, but don't work with path.
Also this thread. And nothing works.
Firstly import the image like this (You can amend it accordingly)
import imageBaseURL = "./assets/images/sampleImages/";
Then inside your ItemList make use of Template Literals like this :
const ItemsList = data.map( item => {
return(
<li><img key={item.id} alt="TitleOfImage" src={`${imageBaseURL}${item.image}`}/></li>
)
})
First step:
Importing image and store it in one variable ( ExampleImg )
import ExampleImg from '../example.png';
Second step:
Inject the image as a src
<img src = { ExampleImg } />
Related
I wanted to inquire about something. I am trying to display staff images, bio, etc.
My query is like so:
const data = useStaticQuery(graphql`
query {
allContentfulStaff {
edges {
node {
staffBio {
staffBio
}
staffImages {
id
gatsbyImageData
description
}
staffOneLine
}
}
}
}
`);
My map function is like so:
return (
<>
<h1>Our Rockin' Staff</h1>
{data.allContentfulStaff.edges.map((node, index) => {
console.log(data.allContentfulStaff);
return (
<div>
<GatsbyImage
key={``}
image={node.gatsbyImageData}
alt={node.description}
/>
{node.staffOneLine}
</div>
);
})}
</>
);
I receive the data from
{node.staffOneLine }, but nothing for the images.
When I console log {data.allContentfulStaff}, I see an array of images that I will attach.
However, I am getting an error which I will also attach… but none of my other queries / functions where I am grabbing images in the same manner are giving me this error and they look relatively similar. I also did not need the image prop in my components as I am using
<GatsbyImage />
Curious if you have any ideas?
node is an array/set of images as staffImages (of 1 position only) is, so you'll need to add directly to each position like:
<GatsbyImage image={item.node.staffImages[0].gatsbyImageData} alt={ 'staff image' } />
You are looping the data correctly as you pointed out with the console.log() but as you can see there, and because your data structure, staffImages is an array of one position (always) that holds the gatsbyImageData so you need to access directly to that position.
The getImage() function discussed in comments is completely optional and it won't change the fact that an image is showing/not showing at all. As you can see in the docs:
import { getImage } from "gatsby-plugin-image"
const image = getImage(data.avatar)
// This is the same as:
const image = data?.avatar?.childImageSharp?.gatsbyImageData
I don't know, I've imported local images before but it isn't working today.
I have this helper file which exports the images as an array
const images = [
require("../assets/1.jpeg"),
require("../assets/2.jpeg"),
require("../assets/3.jpeg"),
require("../assets/4.jpeg"),
require("../assets/5.jpeg"),
require("../assets/6.jpeg"),
]
export default images;
Then I use them here to get a random image here
//Random Image
const randomImg = () => {
console.log(images);
const UU = images[Math.floor(Math.random * images.length)];
return UU;
}
const [hero, setHero] = useState(randomImg());
And then I get hat hero state in my jsx img tag
<img
className="headerImg"
src={hero}
alt="Hero Image"
/>
Why Isn't it working. I'm not using Next or gatsby or anything. I'm using React with webpack 2. Anyone know what is wrong?
Another interesting thing is that if I import a single image like this
import hero from "../../assets/1.jpeg";
And Use It directly in the image
<img
className="headerImg"
src={hero}
alt=""
/>
Suddenly, it works. What is the Problem?
Thanks,
Lakshya
I have a sidebar where it is possible to change the background of the sidebar as a background, I store pictures in the object, everything worked well for me until I decided to add a second property "color" inside the object, that is, in addition to changing the background, the color of the text also changes. it looks like this
I think that the essence is clear, but as I mentioned earlier, the problems started when I decided to add a second property, that is, the color of the text
The problem is that the color property does not work for me, that is, it works, but in this case the sidebar background does not work
My object looks very simple
import Bg from "../../SideBar/Background/mac.jpg"
import Pink from "../../SideBar/Background/pink.jpg"
import Anapa from "../../SideBar/Background/anapa.jpg"
const SideBarBackgrounds = [
{
SideBarWallpaper: Bg,
color: "red",
},
{
SideBarWallpaper: Pink,
color: "green",
},
{
SideBarWallpaper: Anapa,
color: "yellow",
},
].map((item) => {
return {
SideBarWallpaper: item.SideBarWallpaper,
color: item.color,
}
}
)
export default SideBarBackgrounds;
That is, I import the picture and apply it as the value for the SideBarWallpaper properties then create a second property named color and apply the string as the color
Then I use local storage to save the user changes.
export const CounterContext = createContext([]);
export default function ThemeDoc(props) {
const [SideBarBackground, SetSideBarBackground] = useState(JSON.parse(localStorage.getItem("BgKey")));
useEffect(() => {
localStorage.setItem("BgKey", JSON.stringify(SideBarBackground));
})
const ChangeSideBarWallpaper = (SideBarWallpaper) => {
localStorage.setItem('BgKey', JSON.stringify(SideBarWallpaper));
SetSideBarBackground(SideBarWallpaper);
}
return (
<div className="page-wrapper chiller-theme toggled">
<CounterContext.Provider value={{
SideBarWallpaperValue: [SideBarBackground, SetSideBarBackground],
}}>
<SideBar ChangeSideBarWallpaper={ChangeSideBarWallpaper} SideBarPageContent={SideBarPageContent} {...props} />
</CounterContext.Provider>
</div>
);
}
As you can see, I use React Context since I have a lot of themes and I import them in many files, in this case I deleted everything personal and left only the code that belongs to the background of the sidebar
Then I have a component called SideBarWallpaperContainer where I import my object, create a loop using a map, process each property from the object and finally import the SideBarWallpaperContainer component inside the SideBarModal component
export default function SideBarWallpaperContainer(props) {
const SideBarWallpaperList = SideBarBackgrounds.map((theme, index) => {
return (
<img key={index} width={"70"} height={"55"} src={theme.SideBarWallpaper}
className={"SideBar_Appearance_Select_Icon"}
onClick={() => props.ChangeSideBarWallpaper(theme.SideBarWallpaper)} alt={"Select Theme"}/>
);
})
return (
<>
{SideBarWallpaperList}
</>
);
}
SideBarModal.jsx
const DraggableDialog = (props) => {
...
return(
<SideBarWallpaperContainer {...props} />
...
);
}
Through props, I get the ChangeSideBarWallpaper method to change the background and color
And the color for the sidebar text I get using useContext it looks like this
SideBarMenu.jsx
export default function SideBarMenu(props) {
const {SideBarWallpaperValue} = React.useContext(CounterContext);
const [SideBarWallpaperTheme,] = SideBarWallpaperValue;
const SideBarWallpaperStyle = SideBarWallpaperTheme;
return(
<Link
style={{ color: SideBarWallpaperStyle && SideBarWallpaperStyle.color,}}>{item.name}
</Link>
);
}
Now when you roughly understand how all the logic works, I want to explain the problem. The problem is that either the sidebar color or the background does not work for me, please pay attention to the method
props.ChangeSideBarWallpaper (theme.SideBarWallpaper)}
When I use theme.SideBarWallpaper as a parameter inside the ChangeSideBarWallpaper method, only the background works for me and not the color, and this is of course logical, then I tried to apply 2 parameters, the color and the background, it looked like this
onClick={() => props.ChangeSideBarWallpaper(theme.SideBarWallpaper, theme.color)}
But in this case, only the background also worked and the only solution that remained for me to transfer the entire value, it looked like this
onClick={() => props.ChangeSideBarWallpaper(theme)}
And then I was surprised now only the sidebar color works for me but the background does not work, You can look at the picture (sorry if I'm so long and boring to explain :) I just want you to understand the problem as clearly as possible)
I decided to check if I get a picture and yes I get
Now that you understand the problem, I will be interested in hearing your advice, thank you for paying attention to my long question.
Before I demonstrate the solution, I would like to say that the problem lies with me, I, as always, introduced myself impatiently and inattentively: (it turns out that I forgot that in the SideBar component I get the SideBarBackground value in short, the code looked like this
const {someValue} = useContext(SideBarContext);
const {SideBarValue, SideBarWallpaperValue} = React.useContext(CounterContext);
const [SideBarTheme] = SideBarValue;
const [SideBarBackground] = SideBarWallpaperValue;
<div style={{backgroundImage: `url(${SideBarBackground})`}}>
...
</div>
Then I got the SideBarWallpaper value
<div style={{backgroundImage: `url(${SideBarBackground.SideBarWallpaper})`}}>
...
</div>
I have an issue with a component that takes a name property for use as an avatar (replaces spaces with dashes and adds file format). This then gets used as the img src dynamically.
Works absolutely fine locally, no stuttering changing the image. When I bundle and deploy to surge.sh and change routes the image stutters. I expected this as each image needs to be downloaded initially but even after the image is cached, swapping the image is jerky. Any ideas? Or is there a better way to do this?
class Athlete extends Component {
constructor (props) {
super(props);
}
render () {
let name = this.props.name;
let imgName = name.replace(/\s+/g, '-').toLowerCase();
let imgSrc = '/img/athletes/' + imgName + '.jpg';
return (
<div className="winner__inner">
<img src={imgSrc} alt={name} className="winner__avatar"/>
<h3 className="winner__name">{name}</h3>
</div>
);
}
}
export default Athlete;
Link: http://boulder.surge.sh/ (desktop only - click one of the events)
GIF: https://i.gyazo.com/4dea5302d9671b4de0fadc2334f872da.gif
Cached images: https://i.imgur.com/xQLgIWq.png
Any help would be great, thanks!
I have an index of images and titles I am pulling in from the Dropbox api. These (when clicked) already create and mount new components. I'm trying to integrate react-router into this project but am struggling to generate Link to= paths using the array I have already created.
import { BrowserRouter, Route, Link } from 'react-router-dom'
//titles variable created via api
var titles=["title one","title two","title three",...]
class Index extends React.Component{
render(){
if(!this.props.imageSource.length)
return null;
let titles = this.props.imageTitles.map((el, i) => <p>{el}</p>)
let images = this.props.imageSource.map((el, i) =>
<div className="imageContainer">
<img key={i} className='indexImages' src={el} onClick = {this.props.indexTitleClick.bind(this,titles[i])}/>
<Link to={titles[i]} className="imageTitle" onClick = {this.props.indexTitleClick.bind(this,titles[i])}>{titles[i]}</Link>
</div>
)
return (
<div className="indexWrapper">
{images}
</div>
);
}
}
As you can see I'm trying to use the same method as I have for generating the imageTitles, but the href is simply "/" when rendered. Is it possible to dynamically generate paths in this way?
p.s. I've tried to keep the code concise here but happy to add in more info if needed.
Not sure you are aware of that but you overriding titles.
var titles=["title one","title two","title three",...] // from outside your component
let titles = this.props.imageTitles.map((el, i) => <p>{el}</p>) // inside render
Then, you are trying to link to the members of titles array but it holds members in this format:
<p>{el}</p>
First you have to create a Root class where you will declare some paths like the below example
<Router history={browserHistory} >
<Root path="/:pathVariable" component={ComponentClass}/>
</Router>
and then with browserHistory.push("/path") you will navigate to http://host:port/path