How to display an image from a string in react - javascript

I have featured_image that i get from an axios call, the image is saved in the src folder, src/img. It's a string and it's equal to "../img/blog1.jpg".
I can't have the background image dispalyed i believe it needs to be converted to a static image somehow.
import React from "react";
import { Link, NavLink } from 'react-router-dom';
const Post = ({ post: { title,
featured_image, category, slug, summary }, index }) => {
return (
<div>
<div role="listitem" className="post-v1 w-dyn-item">
<div className="post-card-v1">
<Link to={slug} className="post-v1-thumb w-inline-block">
<div className="post-v1-image" style={{backgroundImage: "url(" + featured_image + ")"}}></div>
</Link>
<div className="post-v1-content">
<div className="post-card-more-info">
<div className="badge post-v1-badge">{category}</div>
</div>
<Link to={slug} className="link-white w-inline-block hover-blog">
<h4 className="uppercase text-white">{title}</h4>
</Link>
<div className="text-white">{summary}</div>
</div>
</div>
</div>
</div>
);
};
export default Post;

If you are using static images in react app you better should move them to the public folder
featured_image value example 'img/1.jpg'
assuming you moved the whole folder img to public
Why would i put them in public folder?
answer:
If you put any kind of file into the public folder, it will not be
processed by webpack. it will be copied into the build folder as it
is.
To give the access to all the components/pages to this file(html/img) with one same path no matter is deep the component in folders

Since you're in the brackets, you write js, so you should use string interpolation :
style={{ backgroundImage: `url(${featured_image})`}}

Related

How to add a link to another website after clicking on Card in React JS

Below is my code for Cards.js file, right now it's a card that you can click on and it links to the Services page with path ='/services' from within the same website, I would like to add a link to another website, how would I go about doing that? would I need to add an a href= link to Cards.js?
import React from 'react';
import CardItem from './CardItem';
import './Cards.css'
function Cards() {
return (
<div className='cards'>
<h1>Check out my Programming Portfolio Projects!</h1>
<div className='cards__container'>
<div className='cards__wrapper'>
<ul className="cards__items">
<CardItem
src={`${process.env.PUBLIC_URL}/images/ReactSocialPosts.jpg`}
text='hello testing 123'
label='This is a card'
path ='/services'
/>
</ul>
</div>
</div>
</div>
)
}
export default Cards;
Below is CardItem.js if needed
import React from 'react';
import { Link } from 'react-router-dom';
function CardItem(props) {
return (
<>
<li className='cards__item'>
<Link className='cards__item__link' to={props.path}>
<figure className='cards__item__pic-wrap' data-category={props.label}>
<img
src={props.src}
alt='Travel Image'
className="cards__item__img"
/>
</figure>
<div className='cards__item__info'>
<h5 className='cards__item__text'>{props.text}</h5>
</div>
</Link>
</li>
</>
);
}
export default CardItem;
I'm not sure, but I think that you would only have to create a second CardItem with its attribute path = complete link to external website.
Example :
<CardItem
src={`${process.env.PUBLIC_URL}/images/OtherImage.jpg`}
text='External website'
label='A label'
path ='https://externalwebsite.com'
/>
If you just want to simply link to another website then you can simply use an anchor tag, if you want to declare a Route from react-router-dom for that link to follow, you need to look at this post
As per documentation React-Router understands only internal paths. Then an anchor tag is needed. I would do a wrapper component for Link that chose if render an anchor or the router link object. Then use it instead of "Link".
Something like (code not tested):
const MyLink = ({path, children, ...props}) => {
const comp = path?.trim().substring(0,4) === "http" ? <a href={path}> : <Link to={path}>;
return <comp ...props>{children}</comp>
};

How to pass a dynamic image path to a React card as a prop

I'm trying to pass an image path that is loaded from a database to a React card. I can't do an import (at least it hasn't worked) and I've tried to add require(props.avatar) with no luck. Here's the code and I know the path is hard coded, I haven't got to the database part yet, but this should still work somehow...
App.js looks like this:
class App extends React.Component {
render() {
return (
<div className="ui container comment main-list">
<HeaderCard></HeaderCard>
<SearchBar></SearchBar>
<MainCard className="main">
<MainDetail
Name="Baby Buntings!"
Date="11/12/20"
text="What up!"
**avatar="../images/benefit.jpg"**
Price="$20.00"
/>
</MainCard>
<MainCard>
.
. (more data)
.
MainDetail.js looks like this:
const MainDetail = props => {
console.log(props.avatar);
return (
<div className="comment main-time-place">
<a href="/">
**<img className="main-image" alt="benefit" src={props.avatar} />**
</a>
<div className="content">
<a href="/" className="author">
Featuring: {props.Name}
</a>
<div className="metadata">
<span className="date cardtext">Date: {props.Date}</span>
</div>
<div className="text cardtext">{props.text}</div>
<div className="price cardtext">Price: {props.Price}</div>
</div>
</div>
);
};
export default MainDetail;
This code has this:
src={props.avatar}
but I've also tried
src={require(props.avatar)}
If I do an import with a hard coded path, it works, but I can't do that...
This seems like it should be simple to do. The images are uploaded by users on another page so I won't know what they are in advance so I can't import them. (Or can I???).
Any suggestions would be appreciated. Thanks.

I don't see my picture but only the alt attribute

I don't understand why I cannot see my image, I mean I just see the alt attribute instead of the picture. Here is my code :
import React, {Component} from "react";
const Cards = (props) => {
return (
<>
<div id="card" className={"card text-white bg-" + props.bootstrap + " mb-3"}
style={{maxWidth: 200, marginRight: 10}}>
<div className="card-header">Test</div>
<div className="card-body">
<img src="test.jpg" width="200px" height="200px" className="card-img-top" alt="test" />
<h4 className="card-title">Description</h4>
</div>
</div>
</>
)
}
export default Cards;
whereas when I try this modification it works :
import React, {Component} from "react";
import logo from './test.jpg';
const Cards = (props) => {
return (
<>
<div id="card" className={"card text-white bg-" + props.bootstrap + " mb-3"}
style={{maxWidth: 200, marginRight: 10}}>
<div className="card-header">Test</div>
<div className="card-body">
<img src={logo} width="200px" height="200px" className="card-img-top" alt="test" />
<h4 className="card-title">Description</h4>
</div>
</div>
</>
)
}
I don't understand why this does not work. For me the path is good.
Could you help me please ?
Thank you a lot !
alt will be presented each time the image would not load properly.
So in your case, the latter example would work properly because logo is actually pointing to the jpg image, and the image could be displayed without the alt string.
The first example you shared would not work because src doesn't have an actual pat, it only has a string that isn't resolved into an image hence no image would be loaded and the browser will present the alt value.
on most occasions, images (static files) should be stored in your /public folder.
You can create a images folder in your public folder and then you set src="/images/test.jpg" instead of just "test.jpg"
You need to import
In some case if still not work
than check config file as I described
Note: need to install file-loader package
import React, {Component} from "react";
import logo from './test.jpg';
const Cards = (props) => {
return (
<>
<div id="card" className={"card text-white bg-" + props.bootstrap + " mb-3"}
style={{maxWidth: 200, marginRight: 10}}>
<div className="card-header">Test</div>
<div className="card-body">
<img src={logo} width="200px" height="200px" className="card-img-top" alt="test" />
<h4 className="card-title">Description</h4>
</div>
</div>
</>
)
}
In Config file:: MAKE SURE FOLLOWING RULES DEFINED
module.exports = {
// other config
module: {
rules: [
// other rules
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader'
},
]
}
}```
Try like this:
<img src="./test.jpg" ...
It should work, if the picture is in the public folder.
The answer is : <img src={require('./test.png').default} />
That's because webpack is configured to bundle your images and assets by using the JSX syntax. Anything within {} can be seen as a property of a component. When it's inside the src attribute it becomes a property of the src and webpack than knows what to do. If you are simply adding the string it will view the source as a string rather than an image.
The path alone will only have meaning when you convert it from a meaningless string to an object. An alternative to your first approach could be
<img src={require('/text.jpg')} />
That should work too.

React Image Selector

so I am trying to use an if statement but don't know how to word it properly, or if I can with React in a jsx file. My goal is to select the image based on the first name attribute I chose and worked so here is the code for the App.js I am trying to keep it as simple and basic as possible so I can try to figure out a nice clean way to do it but I have no clue. Thanks :)
import './App.css';
import PersonalCard from './components/personal.jsx'
function App() {
return (
<div className="App">
<PersonalCard firstName="Lou" lastName="Ferrigno" age={68} hairColor="Black" />
<PersonalCard firstName="Arnold " lastName="Schwarzenegger " age={73} hairColor="Brown" />
{/* Franco died in 2019 at the age of 78 :'( */}
<PersonalCard firstName="Franco" lastName="Columbu " age={79} hairColor="Brown" />
<PersonalCard firstName="Frank " lastName="Zane " age={78} hairColor="Black" />
</div>
);
}
export default App;
now here is the code for the jsx file
import React from 'react';
const theW ={
width:'400px',
}
const PersonCard = props => {
const {lastName,firstName,age,hairColor} = props
return(
<div className="card" style={theW}>
<img className="card-img-top" src="" alt="Card image"></img>
<section className="card-body">
<h1 className="card-title">{ lastName }, { firstName }</h1>
<p className="card-text">Age: { age }</p>
<p className="card-text">Hair Color: { hairColor }</p>
See Profile
</section>
</div>
);
}
export default PersonCard;
you just need to add the src attribute of the image as dynamic.
so in your code
div className="card" style={theW}>
<img className="card-img-top" src={`location/${firstname}.jpg`} alt="Card image"></img>
here location is the path to the file
EDIT
webpack require additional files to be imported so
<img className="card-img-top" src=require({`location/${firstname}.jpg`}) alt="Card image" />
Thank you so much for trying # Sharun K K but even though it might have been something I was doing wrong that require way did not work for me.
What I did to fix this and shout out to this video on youtube Esterling Accime!,was instead I added an image folder in the public section and did this line of code
<img className="card-img-top" src={`/images/${firstName}.jpg`} />
so that worked wonders for me once again thank you so much for the help :). Another issue with this was I put a name in the App.js file I did this
// this is wrong because of the space in the firstName
<PersonalCard firstName="Lou " lastName="Ferrigno" age={68} hairColor="Black" />
// so no spaces like this
<PersonalCard firstName="Lou" lastName="Ferrigno" age={68} hairColor="Black" />
// and all my issues went away.

How to change the background-color of an element that is inside a GatsbyJS component, based on the page where I import the component?

It's the first time I'm building a website with GatsbyJS and I'm trying to build some components to use all over the site.
One of these components is the footer. I wrote its structure but I want to change the color of a <div> that is part of the footer based on which page am I visiting. I don't want the whole footer to change color, only this div that is part of the footer.
To be more accurate: if I'm visiting the Homepage I want this div to have an orange Background whereas if I'm inside the contact page I want it to have a blue background.
Is it possible?
This is part of the code of my footer (that is the footer.js gatsby component that I import in my pages):
<footer className={footerStyle.footer}>
<div className={footerStyle.parteSopra}>
<div className={footerStyle.parteSopra}>
<div className={footerStyle.ottanta}>
<h3 className={footerStyle.rimaniamo+ ' '+footerStyle.dimTitoli}>rimaniamo<br />in contatto</h3>
</div>
<div className={footerStyle.venti}>
</div>
</div>
<div className={footerStyle.parteSotto}>
<div className={footerStyle.ottanta+ ' '+footerStyle.boxFrecciaBlu}>
<div className={footerStyle.contieniFrecciaBlu}>
<img className={footerStyle.frecciaBlu} src={frecciaBlu} alt="Freccia giù" />
</div>
</div>
<div className={footerStyle.venti+ ' '+footerStyle.boxFbEInstaBlu}>
<div className={footerStyle.contieniFbBlu}>
<a href="https://it-it.facebook.com/DiamanteCalzature" target="_blank" rel="noopener noreferrer">
<img className={footerStyle.fbBlu} src={iconaFbBlu} alt="Facebook" />
</a>
</div>
<div className={footerStyle.contieniInstaBlu}>
<a href="https://instagram.com/diamantecalzature?igshid=cta3uh8iob7a" target="_blank" rel="noopener noreferrer">
<img className={footerStyle.instaBlu} src={iconaInstaBlu} alt="Instagram" />
</a>
</div>
</div>
</div>
</div>
<div id="coloreFootSotto" className={footerStyle.parteSotto+ ' '+footerStyle.coloreFooterSotto}>
<div className={footerStyle.ottanta}>
</div>
<div className={footerStyle.venti+ ' '+footerStyle.boxTornaSu}>
</div>
</div>
</footer>
I import it in my pages writing <Footer /> and I thought I could add an attribute, a prop, or something inside that tag to realize what I want. I need the div with Id id="coloreFootSotto" to have a different background-color based on the page I am visiting. At the moment I'm just manipulating the DOM in some pages to change the background-color but I was wondering if it is possible to do it with props or something like that (maybe not).
Does anyone know it?
Thank you
Gatsby uses reach router so you can use useLocation in your component and do something with the location.pathname for specific routes.
// Footer.js
import React from 'react';
import { useLocation } from "#reach/router"
import Container from 'components/Container';
const Footer = () => {
const {pathname} = useLocation()
console.log(pathname)
return (
<footer style={pathname=== '/' ? {backgroundColor: 'blue'} : null} >
<Container>
<p>© {new Date().getFullYear()}, My Gatsby Site</p>
</Container>
</footer>
);
};
export default Footer;
It's also worth mentioning that you can get location data from a gatsby page via its location prop.
Depending on how your app is structured, you could also get this data from your page component, and pass the relevant data down via props down through your component tree.
eg IndexPage > Layout > Footer
For multiple pages, you could do something like this.
// Footer.js
import React from 'react';
import { useLocation } from "#reach/router"
import Container from 'components/Container';
const pagesWithColoredFooter = ['/', '/page-2', 'page-3'];
const Footer = () => {
const {pathname} = useLocation()
console.log(pathname)
return (
<footer style={pagesWithColoredFooter.includes(pathname) ? {backgroundColor: 'blue'} : null} >
<Container>
<p>© {new Date().getFullYear()}, My Gatsby Site</p>
</Container>
</footer>
);
};
export default Footer;

Categories

Resources