I have a little bug in my app and can't fix it.
I need to render images from JSON.
First of all, I have a number of albums:
AlbumLayout
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link, browserHistory } from 'react-router';
class AlbumLayout extends Component {
handleClick(album){
browserHistory.push({
pathname: "album/" + album.id,
state: {albumDetails: album}
});
}
renderList(){
return this.props.albums.map((album) => {
return(
<li onClick={this.handleClick.bind(this, album)} key={album.id}>
<img alt="job" src={album.img} />
<p className="album_titulo">{album.title}</p>
</li>
);
});
}
render(){
return (
<div>
<div className="albums">
<div className="albums_caixa">
<div className="row">
<div className="col-xs-12">
<ul className="no_pad">
{this.renderList()}
</ul>
</div>
</div>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state){
return {
albums: state.album
};
}
export default connect(mapStateToProps)(AlbumLayout);
Every albums has own list of images:
List of images
import React, { Component } from 'react';
import { connect } from 'react-redux';
class AlbumsShow extends Component {
renderImage(mainData, imageIdx){
let jobDetails = this.props.albums.filter( t => t.id == this.props.params.id)[0];
return (
<div key={imageIdx} className='content'>
{mainData.images.map((image, etag) => {
return(
<div key={image.etag} className='content_box'>
<img key={image.etag} src={image.images.smallThumbnail} alt="book"/>
</div>
)
})}
</div>
)
}
render(){
return (
<div>
{this.props.image.map(this.renderImage)}
</div>
);
}
}
function mapStateToProps({image}) {
return {image};
}
export default connect(mapStateToProps)(AlbumsShow);
When user click on any Album, he should see list of images, which is parsing from JSON.
{
"images": {
"id": "01",
"etag": "01",
"images": {
"kind": "image",
"id": "1",
"etag": "1",
"smallThumbnail": "http://books.google.com/books/content?id=FaaQgVCaXU4C&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api"
}
}
}
As for me, I have mistake in List of images-file, but I can't find it.
I will really appreciate for any help.
Thanks!
I think you may just need to bind the this context in your .map function:
return (
<div>
{this.props.image.map(this.renderImage.bind(this))}
</div>
);
It also looks like you might need to add albums to your connect in that component.
Related
The following error shows up when I run my react code: TypeError: Cannot read property 'comments' of undefined. I am trying to eradicate this error but can't do so. Is this because I have not mapped my array correctly or do I need to add in some more code? Please Help!!!!!!!
This is my MainComponent file:
import React, { Component} from 'react';
import { Navbar, NavbarBrand } from 'reactstrap';
import { DISHES } from '../shared/dishes';
import Menu from './menucomponent';
import DishDetails from './dishdetail'
class Main extends Component {
constructor(props) {
super(props);
this.state = {
dishes: DISHES,
selectedDish: null
};
}
onDishSelect(dishId) {
this.setState({
selectedDish: dishId
});
}
render() {
return (
<div>
<Navbar dark color="primary">
<div className="container">
<NavbarBrand href = "/" > Ristorante Con Fusion </NavbarBrand>
</div>
</Navbar>
<Menu dishes={this.state.dishes}
onCick = {(dishId) => this.onDishSelect(dishId)} />
<DishDetails dish={
this.state.dishes.filter((dish) => dish.id === this.state.selectedDish)[0]
}/>
</div>
);
}
}
export default Main;
This is my DishDetail file:
import React, { Component } from 'react';
import {
Card,
CardImgOverlay,
CardImg,
CardBody,
CardText,
CardTitle,
CardHeader
} from 'reactstrap';
import { Media } from 'reactstrap';
class DishDetail extends Component {
constructor(props) {
super(props);
}
render() {
const como = this.props.dishes.comments.map((dish) => {
return (
<div className="container">
<div key={dish.id}>
<p>
{dish.comment}
<br/>
--{dish.author},
{
new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: '2-digit'
}).format(new Date(Date.parse(dish.date)))
}
<br/>
</p>
</div>
</div>
);
});
return (
<div>
<div className="row">
<div className="col-12 col-md-5 m-1">
<Card>
<CardImg src={this.props.dish.image}
alt={this.props.dish.name}/>
<CardBody>
<h3> {this.props.dish.name} </h3>
<CardText>{this.props.dish.description}</CardText>
</CardBody>
</Card>
</div>
<div className="col-12 col-md-6">
<p> Comment </p>
<Media list>{como}</Media>
</div>
</div>
</div>
);
}
}
export default DishDetail;
I believe your dishes object contains comment array
change with below the line in your render method first line
const como = this.props.dishes && this.props.dishes.comments.map((dish) => {
DishDetails is expecting a dishes prop. But in your main component, you are giving DishDetails a dish prop.
DishDetail file:
this.props.dishes.comments.map // here we are referencing 'dishes'
Main file:
DishDetails dish = { // here we are referencing 'dish'
this.state.dishes.filter((dish) => dish.id === this.state.selectedDish)[0]
}
/>
Using React Prop Types, Typescript or Flow can help you to avoid spelling errors like this in future. PropTypes would be the easiest to get started with for now.
You call the dishes while you must to call the dish
this.props.dish.comments.map
Good evening,
I have the following JSON structure:
"Flow": [
{
"title": "Is your multicloud secure and scalable?",
"icon": "<FontAwesomeIcon className='my-icon' icon={faShieldCheck} />"
}
],
As you can see, it uses the React version of FontAwesome Pro. But I need to render this dynamically into a Component.
So far I've tried with different approaches. For example:
<div dangerouslySetInnerHTML={ { __html: item.icon } }></div>
Also tried this:
<div> { ReactHtmlParser(item.icon) } </div>
But no luck so far.
I would appreciate any new ideas on this matter.
Thanks in advance.
Remove the quotes in your json for icon.
In fact, just provide the name of the icon in the json and use require to import the icon while rendering FontAwesomeIcon.
Working demo
Code snippet
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
const myJson = {
Flow: [
{
title: "Is your multicloud secure and scalable?",
icon: "faHighlighter"
}
]
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<FontAwesomeIcon
className="my-icon"
icon={require("#fortawesome/free-solid-svg-icons")[myJson.Flow[0].icon]}
/>
</div>
);
}
Note - below is cleaner code but it imports all icons before hand.
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
const icons = require("#fortawesome/free-solid-svg-icons");
const myJson = {
Flow: [
{
title: "Is your multicloud secure and scalable?",
icon: "faHighlighter"
}
]
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<FontAwesomeIcon className="my-icon" icon={icons[myJson.Flow[0].icon]} />
</div>
);
}
I want to pass my data from one page to another but in an specific way.
I have a json brought via AJAX with this method (resp, error and result):
myArrayItems
import React, { Component } from 'react';
import logo from '../images/logo.png';
import '../App.css';
import { Container, Row, Col } from 'react-bootstrap';
import { Route, IndexRoute } from 'react-router';
import { BrowserRouter as Router, Switch, Link } from 'react-router-dom';
class myArrayItems extends Component {
componentDidMount() {
fetch("https://myrestserver/myArrayItems")
.then(response => response.json())
.then(
(result) => {
console.log(result)
this.setState({
isLoaded: true,
items: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
And in my View i rendered like that with key.
<ul>
{items.map(item => (
<li key={item.title} className="list-group-item border-0">
<div className="wrapper">
<div className="myclass">
<Link to={{ pathname: "/myitem/" }} className="App-link">
<p className="text-left">{item.title}</p>
</Link>
</div>
</div>
</li>
))}
</ul>
}
export default myArrayItems;
So I want to pass the item.id, item.title, item.x to the page myitem, but i imported the myArrayItems and still get undefined.
What I want to achieve is in my first class to display a list of items (What i did) but when i click on any of these items, to access them in the page myitem.
myitem.js
import React, { Component } from 'react';
import logo from '../images/logo.png';
import '../App.css';
import { Container, Row, Col } from 'react-bootstrap';
import { Route, IndexRoute } from 'react-router';
import myArrayItems from './myArrayItems';
const Background = {
background: '#004272'
}
class myitem extends Component {
render(){
return (
<div className="App">
<header style={Background} className="text-center py-2 m-0">
<img src={logo} className="img-fluid w-75"/>
</header>
<Container>
<ul>
<p>{item.title}</p>
</ul>
</Container>
</div>
);
}
}
export default myitem;
I hope you can help me with that, thanks!
UPDATE:
I'm creating a WebApp using ReactJS Library with "npx create-react-app".
I want to map of over object instead of Array, my current code works great with Array map but I am getting data undefined if I map object using state props with redux.
My JSON Format:
{
"exclusive_collection": {
"id": "0",
"image_url": "media/mobilebanner/default/ExclusiveCollection-en_new.jpg"
},
"exclusive_brands": [
{
"id": "1268",
"is_featured": "0",
"name": "Spongelle",
"image_url": "media/catalog/category/Spongelle.jpg"
},
{
"id": "756",
"is_featured": "0",
"name": "Black Up",
"image_url": "media/catalog/category/Black-Up.jpg"
},
],}
Reducer function :
export function items(state = [], action) {
switch (action.type) {
case 'ITEMS_FETCH_DATA_SUCCESS':
return action.items;
default:
return state;
}
}
Child Component:
import React, { Component } from 'react';
import Slider from "react-slick";
class ShopbyCategory extends Component {
render() {
let shopbycategoryArray = [];
let shop_by_category = this.props.items.shop_by_category
for (let key in shop_by_category) {
shopbycategoryArray.push(shop_by_category[key]);
return (
<section className="celebrityslider">
<div className="row">
<div className="widget-title"><h3>Shop By Category</h3></div>
</div>
<div className="row">
<div className="col-md-12 no-padding">
<Slider {...slidersettings}>
{this.props.items.shop_by_category.map((item) => (
<div key={item.id} className="slider-item">
<img src={item.image_url} className="img-responsive"/>
</div>
))}
</Slider>
</div>
</div>
</section>
);
}
if (this.props.hasErrored) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.props.isLoading) {
return <p>Loading…</p>;
}
return (
null
);
}
}
I am able to get the data of exclusive_brands array with the code above in my component.
But I am not sure how to get the data of exclusive_collection I am always getting undefined if I am doing the below :
let exclusive_collection = this.props.items.exclusive_collection
console.log (exclusive_collection);
I would appreciate if someone can help me to map this with redux or in other way. Thanks
I want to use JSON to retrieve my images along with their file location. My program looks like the code below.
I've tried with {photos.Lillian.portfolioImage} and with JSON.stringify(photos.Annalise.portofolio however, none of them can display the images. I've done a console.log(); and checked if the data can be read and it does appear however, the images will not appear. I've checked the source address and it works when I add it here <img src="./img/TheGuardian/Lillian.png">.
What is my error? Do I need to reformat the object called from JSON? I've seen one can use parse and fetch however, this is used for APIs and as far as I can see, this isn't?
Here's my JSON:
{
"Lillian" : {
"type": "The Guardian",
"portfolioImage": "./img/TheGuardian/Lillian.png"
},
"Annalise" : {
"type": "TheGuardian",
"portfolioImage": "./img/TheGuardian/Annalise.png"
},
"Raven" : {
"type": "DCComics",
"portfolioImage": "./img/TheGuardian/Raven.png"
}
}
Here's my HTML:
import React, { Component } from 'react';
import logo from './logo.svg';
import photos from './images.json';
import './App.css';
class App extends Component {
render() {
console.log(JSON.stringify(photos.Annalise.portfolioImage));
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>beeccy´s portfolio.</h2>
</div>
<p className="App-intro">
This was a test to present images from my portfolio.
</p>
<img src={photos.Lillian.portfolioImage} alt="Lillian" />
<img src={photos.Raven.portfolioImage} alt="Raven" />
<img src="JSON.stringify(photos.Annalise.portfolioImage)" alt="Annalise" />
</div>
);
}
}
export default App;
Like in HTML, you want to set the src attribute of an img element the source to the image. The following example also shows how you can loop over the JSON and show all images at once.
const JSON = {
Lillian: {
type: 'The Guardian',
portfolioImage: './img/TheGuardian/Lillian.png'
},
Annalise: {
type: 'TheGuardian',
portfolioImage: './img/TheGuardian/Annalise.png'
},
Raven: { type: 'DCComics', portfolioImage: './img/TheGuardian/Raven.png' }
};
class Example extends React.Component {
render() {
return (
<div>
{Object.keys(JSON).map(key => (
<div>
{JSON[key].type}
<img src={JSON[key].portfolioImage} key={key} />
</div>
))}
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById('root'));
const obj =
{
"Lillian" : { "type": "The Guardian", "portfolioImage": "./img/TheGuardian/Lillian.png" },
"Annalise" : { "type": "TheGuardian", "portfolioImage": "./img/TheGuardian/Annalise.png" },
"Raven" : { "type": "DCComics", "portfolioImage": "./img/TheGuardian/Raven.png" }
};
let images = [];
for(let item in obj){
images.push(item.portfolioImage);
}
By doing this you can retrieve images from the object of objects into the images array