React returns image src as object - reactjs

I have a variable defined like this:
const team = [
{
name: "Foo",
bio: "FooBar",
image: { foo }
},
{
name: "Bar",
bio: "FooBar",
image: { bar }
},
];
Where the images are imported like this:
import foo from "../assets/foo.jpg";
import bar from "../assets/bar.jpg";
These are then passed to a component to be rendered, with:
<TeamRow team={team} />
The TeamRow component looks like this:
const TeamRow = props => {
const items = props.team.map((item, index) => {
return (
<div className="col-10 col-sm-4 col-md-1 mx-auto text-center">
<div className="row">
<div className="col-12 teamMemberImage">
<img className="img-fluid" src={item.image} />
</div>
</div>
<div className="row">
<div className="col-12">{item.name}</div>
</div>
<div className="row">
<div className="col-12">{item.bio}</div>
</div>
</div>
);
});
return <div className="row">{items}</div>;
};
export default TeamRow;
The images fail to render. When I look at them in the dev tools, they have src="Object object". The class that calls TeamRow, is the class in which team is defined. After defining it, calling console.log(foo returns the url pointing to the image, as expected. Somehow, in being passed to the second component, the expected behaviour ceases.
Strangely, earlier, I was using the react logo as a placeholder. So:
import logo from "../assets/logo.svg";, and this worked, but only if I rendered it as src={item.image.logo}.

{ foo } is shorthand for { foo: foo }, and { bar } is shorthand for { bar: bar }.
Instead of putting the image url in an object with a key that will be different for every image, you can set it as the image property directly.
const team = [
{
name: "Foo",
bio: "FooBar",
image: foo
},
{
name: "Bar",
bio: "FooBar",
image: bar
},
];

team[0].image is an object on the form {"foo":"yourUrl"} because you've wrapped foo in brackets, which uses the object shorthand syntax to create a property named foo with the value in variable foo. Remove the brackets around foo and bar

You don't need to put your image files alias names inside the {foo}, you can just write image: foo otherwise it will return as [object object].

In my case, I was struggling for the last four hours. but, it was a Next JS project so I need to put the image properties in an image component.
<Image src={props.img} /> instead of <img>

Related

Icons not showing in react when using material-icons using cdn instead showing their text

I am using react with material-icons without npm as I am using cdn link .
Now I have saved their tags in a external file and calling them in a component but instead of showing icons they are showing their text.
This is my array that I am calling
export const LeftbarTop = [
{
id: 1,
name: "Apps",
icon:<span className="material-icons-outlined">
widgets
</span>,
},
{
id: 2,
name: "Help",
icon: <span className="material-icons-outlined">
help_outline
</span>,
},
];
This is my component through which I am calling this file/array
import {LeftbarTop} from '../../data/sidebar_activity'
function Leftbar(){
const arr = [...LeftbarTop];
return (<>
<div className="leftbar">
<div className="leftbar-topbar">
{arr.map(ele => <LeftList arr={ele}/>)}
</div>
<div className="leftbar-bottombar"></div>
</div>
</>)
}
this is my LeftList component that simply shows that data
function LeftList ({arr}){
return (
<div >
<div >{arr.icon}</div>
{arr.name && <label>{arr.name}</label>}
</div>
)
}
this whole shows icons as
widgets Apps
help_outline Help

Adding an image and an anchor tag to an element within an array using props in React

While creating cards and using props in React.js I need to add an anchor tag(website:) and an image (image:) within a few elements in an array but am unable to figure out how. Of course, as seen below simply just adding an anchor tag etc does not work. Any help would be appreciated.
const projects = [
{
id: 1,
image: <img src="https://picture.jpg" alt="Coaching Website">
name: "Personal Coaching Website",
meaning:"A comprehensive website for a personal health and wellness coach"
website:
},
Rather than defining elements in an array, use the values, and map into the properties of the element.
const projects = [
{
id: 1,
image: "https://picture.jpg",
name: "Personal Coaching Website",
meaning: "A comprehensive website for a personal health and wellness coach",
website: "https://www.samplewebsite.com"
}
];
export default function App() {
return (
<div>
{projects.map(project => {
return (
<div>
<img src={project.image} />
<a href={project.website} />
</div>
);
})}
</div>
);
}

How to render html template with variables inside from in react?

i am fetching html template from server.That template also have object data inside. I want to show that template in react component. I manage to show all the html elements with html-react-parser plugin, but my variables renders like string {data.title}.
const Template = ({templateData}) => {
const [data, setData] = useState({
title: 'Some title',
description: 'Some description'
})
return(
<Fragment>
{HtmlParser(templateData)}
</Fragment>
)
};
Compiles to:
<div>
<div class="title">{data.title}</div>
<div class="description">{data.description}</div>
</div>
Wanted result:
<div>
<div class="title">'Some title'</div>
<div class="description">'Some description'</div>
</div>
EDIT: found solution but it doesn't look like a good one :)
I replaced strings with variable.
HtmlParser(templateData
.replace(/{data.title}/g, data.title)
.replace(/{data.description}/g, data.description))

Display images dynamically using map() in react not working

I want to display images in the sports array using map(). but not working
<div className="row">
{this.state.sports.map(function(sport, index){
return (
<div className="col-md-3" key={index}>
<h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') } width="300px" height="180px" />
<button className="btn btn-info btn-sm" type="submit" onClick={this.join_in_sport} >JOIN</button>
</div>
)
}.bind(this))}
</div>
The problem seems to lie in how you are building the pathname for your image. Same for your <h3> tag.
src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') }
If this.state.sports is an array, and not an object, then it can't possibly have a name key. I think you meant to print the current objects name for each iteration in your map().
So try:
<h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {sport.name} +'.jpg') } width="300px" height="180px" />
This is assuming your array looks something like:
[
{name: "foo"},
{name: "bar"}
]
I have encountered the same problem,
the image folder in src doesn't work.
I moved the image folder to public and it works fine.
function App() {
const moviesData = [
name: "Terminator: Dark Fate",
img: "./badboy3.jpg", //image in public folder
},
];
const movieList = moviesData.map((movie, i) => {
return <Movie key={i} movieName={movie.name} movieImg={movie.img} />;
});
return (
<div>
{movieList}
</div>
);
}
export default App;
I was following the React beginners tutorial tried to call images dynamically by importing them as variables but this simply didn't work when trying to call them in another file (App.js) using the .map() function. Code below:
import katieImg from "../images/Katie.png";
import starImg from "../images/Katie.png";
export default [
{
img: { katieImg },
star: { starImg },
rating: "5.0",
reviewCount: 6,
location: "USA",
title: "Life Lessons with Katie Zaferes",
price: 136,
},
];
So instead I had to get rid of the dynamically imported variables and put the images folder in the public folder. This worked. Code below:
export default [
{
img: "../images/Katie.png",
star: "../images/Star.png",
rating: "5.0",
reviewCount: 6,
location: "USA",
title: "Life Lessons with Katie Zaferes",
price: 136,
},
];

Render map not displaying data on screen

I can't seem to get my renderJob mapping to render out properly. I have no errors in the console and can't figure out while nothing is showing up. Is there a problem with the way I'm mapping the object to the index?
import React, { Component } from 'react'
import PropTypes from 'prop-types'
const jbSampleData = [
{
name: 'A place',
location: 'USA',
engineer: "Contact Engineer",
service: "Last install"
},
]
class Job extends Component {
render() {
const renderJob = this.props.data.map((obj, idx) => {
return (
<div key={idx}>
<div>
<p>
<span>Name:</span> {obj.name} < br/>
<span>Location:</span> {obj.location} <br />
<span>Engineer Contact:</span> {obj.engineer} <br />
<span>Service:</span> {obj.service} <br />
</p>
</div>
</div>
);
});
return (
<div>
<renderJob />
Hello
</div>
)
}
}
Job.propTypes = {
data: PropTypes.arrayOf(
PropTypes.object
)
}
Job.defaultProps = {
data: jbSampleData
}
export default Job;
You are storing the map result basically an array in a variable renderJob, that is not a react component.
You need to render it like this:
return (
<div>
{renderJob}
Hello
</div>
)
Basically <renderJob> will get converted into:
React.createElement(renderJob, null); //new custom element
But in case of {renderJob} its value will get replaced, and all the ui items that variable is having will get rendered.
Why it is not throwing the error with <renderJob/> ?
Because name is stated with small letter so it will be considered as a built-in component like div etc, if you use <RenderJob/> it will throw error that RenderJob is not defined.
As per DOC:
When an element type starts with a lowercase letter, it refers to a
built-in component like <div> or <span> and results in a string 'div'
or 'span' passed to React.createElement. Types that start with a
capital letter like <Foo /> compile to React.createElement(Foo) and
correspond to a component defined or imported in your JavaScript file.
Instead of <renderJob /> change to {renderJob}

Resources