React passing import name as prop on img src passing as string
Try this...
<MyComponent myprop={Myimage} />
React passing import name as prop and adding to image src
Two components - App.js and Icon.js and an image called icon.jpg
Here is your App.js
import React from 'react';
import icon from './icon.jpg';
import Icon from './Icon';
const App = () => (
<div>
<h1>This is the app</h1>
<Icon icon={icon} />
</div>
);
export default App;
And here is your Icon.js
import React from 'react';
const Icon = props => (
<div>
<p>This is the icon</p>
<img src={props.icon} alt="" />
</div>
);
export default Icon;
Here is a working example: https://codesandbox.io/s/4z64wyqnn9
Set image src with props
PUBLIC FOLDERConsidering you have a public folder structured as followed,
- public
|- images
|- image.jpg
You can structure your components as such:
const App = () => (
<ProjectCard image="image.jpg" />
);
const ProjectCard = (props) => (
<div>
<img src={`images/${props.image}`} />
</div>
);
Where your image path will simply be absolute to the public folder, as images/image.jpg
SRC FOLDER
On the other hand, if you have your images inside your src folder as followed,
- src
|- components
|- ProjectCard.jsx
|- images
|- image.jpg
App.jsx
You can structure your components as such:
import image from "./images/image.jpg";
const App = () => (
<ProjectCard image={image} />
);
const ProjectCard = (props) => (
<div>
<img src={props.image} />
</div>
);
Image not loading when passing a prop to <img src="this.prop." /> in React
As recommended by Xuscrus, I linked my images using the public path. I had to remove my absolute path in order for this solution to work.
I moved all of my images inside a folder named "img" inside the public folder of my create-react-app.
With the example used in my initial statement, here is the easiest solution I found:
import React from 'react';
export class Products extends React.Component { render() { return( <div className="products"> <img src={`/img/${this.props.product.src}.png`} width="50" /> <h6>{this.props.product.name}<span className={`block ${this.props.product.color}`}></span></h6> </div> ) }}
Passing URL of local image as a prop to component in React
I found the answer.
Turns out, these are the changes I made.
- In my projects array, instead of passing the Url as a string to my
imageUrl
, I passed the string to therequire()
method, which in turn comprised of theimageUrl
const projects = [
{
id: 1,
title: "Project 1",
imageUrl: require("../assets/images/free-stock-image-1.jpg"),
excerpt: "This is my project about...",
},
{
id: 2,
title: "Project 2",
imageUrl: require("../assets/images/free-stock-image-2.jpg"),
excerpt: "This is my project about...",
},
{
id: 3,
title: "Project 3",
imageUrl: require("../assets/images/free-stock-image-3.jpg"),
excerpt: "This is my project about...",
},
];
- In the receiving component
ProjectCard
, the require methods returns an object. To utilise the image in the object, simply add .default to the prop as:
import React from "react";
function ProjectCard(props) {
const { title, excerpt, imageUrl } = props;
return (
<div className="card shadow h-100">
<img className="card-img-top" src={imageUrl.default} alt="Project" />
<div className="card-body">
<h4 className="card-title">{title}</h4>
<p className="card-text">{excerpt}</p>
<a href="/" className="stretched-link"></a>
</div>
</div>
);
}
export default ProjectCard;
That solved my query!
How to pass Image object as props in React?
Issueprops.firstImage.icon
isn't defined in the ThreePanel
component as the image was passed as panelOne={{ icon: {firstImage}, name: "First" }}
. This means the child component would need to access props.panelOne.icon.firstImage
to get to the image. This may work if each Panel
component is passed the correctly nested property.
<Panel cardData={props.panelOne.icon.firstImage} />
<Panel cardData={props.panelTwo.icon.secondImage} />
...etc...
As you can see, each child panel needs to know which panel it is, but also needs to know what the image property was named. This isn't ideal.
SolutionYou should strive to pass consistently named props down to "repeated" children as each "instance" won't be aware which dynamic prop they should access. In this case it's the value passed that is dynamic, not the prop key.
Home
Pass the dynamic image values on a standard prop, like icon
.
import firstImage from '../public/images/one.png';
import secondImage from '../public/images/two.png';
import thirdImage from '../public/images/three.png';
export default function Home() {
return (
<ThreePanel
panelOne={{ icon: firstImage, name: "First" }}
panelTwo={{ icon: secondImage, content: "Second" }}
panelThree={{ icon: thirdImage, content: "Third" }}
/>
)
}
ThreePanel
Access the "dynamic" panel prop to pass the specific panel prop object to each Panel
component. Now the intermediate ThreePanel
component doesn't need to know much of the deeper nested values, it knows to pass 1 of 3 panel prop objects to it's 3 panel children.
export default function ThreePanel(props) {
return (
<Grid container>
<Grid item>
<Panel cardData={props.panelOne} />
</Grid>
<Grid item>
<Panel cardData={props.panelTwo} />
</Grid>
<Grid item>
<Panel cardData={props.panelThree} />
</Grid>
</Grid>
)
}
Panel
Now the passed carData
prop will be the specific image that was passed from grandparent/ancestor component. Notice here that each individual panel doesn't know which of the 3 panels it is, but it knows it has an image icon prop to access.
export default function Panel(props) {
return (
<Image
src={props.cardData.icon}
height="170em"
/>
)
}
(Gatsby) How to pass image source as a prop in MDX component
Hat tip to Ferran for helpful guidance.
After more research, I revised my solution—
articleTemplate.js
/* shortcodes */
const ArticleTemplate = ({ data, location }) => {
let post = data.mdx
return (
<Layout location={location}>
<Seo
title={post.frontmatter.title}
description={post.frontmatter.lead}
date={post.frontmatter.computerDate}
/>
<article className="article">
<p className="date">
<time dateTime={post.frontmatter.computerDate}>{post.frontmatter.humanDate}</time>
</p>
<h1 itemprop="headline">{post.frontmatter.title}</h1>
<p className="lead" itemprop="introduction">{post.frontmatter.lead}</p>
<MDXProvider components={shortcodes}>
<MDXRenderer
data={post.frontmatter.thumbnail}
localImages={post.frontmatter.embeddedImagesLocal}
>
{post.body}
</MDXRenderer>
</MDXProvider>
</article>
</Layout>
)
}
export default ArticleTemplate
export const pageQuery = graphql`
query ArticleBySlug($id: String!) {
site {
siteMetadata {
title
}
}
mdx(id: {eq: $id}) {
id
excerpt(pruneLength: 160)
body
frontmatter {
title
computerDate: date(formatString: "YYYY-MM-DD")
humanDate: date(formatString: "D. MMMM YYYY", locale: "nb")
hook
type
lead
thumbnail {
childImageSharp {
gatsbyImageData(
layout: FULL_WIDTH
)
}
}
embeddedImagesLocal {
childImageSharp {
gatsbyImageData
}
}
}
}
}
`
figure.js
import * as React from "react"
import { GatsbyImage, getImage } from 'gatsby-plugin-image'
const Figure = ({ source, size, caption, credit }) => {
return (
<figure className={size}>
<GatsbyImage image={getImage(source)} alt={caption} />
<figcaption>
<span>{caption}</span>
<span>{credit}</span>
</figcaption>
</figure>
);
}
export default Figure
index.mdx
---
…
thumbnail: "thumb.jpeg"
embeddedImagesLocal:
- "first.jpeg"
- "second.jpeg"
---
<Figure
source={(props.localImages [0])} <!-- first image; second image would be `[1]` -->
size="I'm a `className`"
caption="I'm a caption"
photographer="I'm a name."
/>
(Marking this as the solution as it's the most helpful for anyone looking to do this in the future. It also shows how to query for embedded images and featured images—at the same time.)
Related Topics
How to Calculate the Sum of Table Column in Angular 2+
Print Embedded Pdf from Browser With Javascript, Html5, Angularjs
How to Assign [(Ngmodel)] With an Empty/Null/Undefined Object - Angular 4
Reprompt for Permissions With Getusermedia() After Initial Denial
If a Div Contains a Specific String of Text, Edit the Parent'S CSS
React Hooks Error: Hooks Can Only Be Called Inside the Body of a Function Component
Hide Elements If User Logged In
Can We Cast a Generic Object to a Custom Object Type in JavaScript
Setting the Value of a Checkbox Input If Not Checked
Mobile Safari: Why Is Window.Scrollto(0, 0) Not Scrolling to (0, 0)
Javascript: How to Redirect a Page After Validation
How to Avoid the Setstate()/Render() Endless Loop When Passing Data from Child to Parent
Jest Encountered an Unexpected Token: Syntaxerror: Unexpected Token {
Show Multiple Divs on Button Click
How to Take Screenshot of a Div With JavaScript
How to Show an Alert After Reloading the Page in JavaScript