how to display all image in array react js - javascript

how to display Img array all image in react js
data***
import im1 from "../Image/10007.jpg"
export const Data =[
{
name:"aminur",
Img:[im1,im1,im1]
}
]enter code here
code :
import React from 'react'
import "./Content.css"
import { Data } from './data'
const Content = () => {
return (
<div className='content'>
{Data.map((item)=>{
return(
<div className='text'>
<img src={item.Img[0]} alt="" />
</div>
)
})}
</div>
)
}
export default Content

What I understood from your question is how to display all the images under Img array which is inside an another array of objects.
import React from 'react'
import "./Content.css"
import { Data } from './data'
const Content = () => {
return (
<div className='content'>
{Data.map((item)=>{
return(
<div className='text'>
{item?.Img.map(image=>(
<img src={image} alt="" />
))}
</div>
)
})}
</div>
)
}
export default Content

Related

React conditional styling in a map function problem

I just want to show toggled item. But all map items showing up. Basically this is the result I'm getting from onclick. I think i need to give index or id to each item but i don't know how to do it. i gave id to each question didn't work.
App.js.
import "./App.css";
import React, { useState, useEffect } from "react";
import bg from "./images/bg-pattern-desktop.svg";
import bg1 from "./images/illustration-box-desktop.svg";
import bg2 from "./images/illustration-woman-online-desktop.svg";
import { data } from "./data";
import Faq from "./Faq";
function App() {
const [db, setDb] = useState(data);
const [toggle, setToggle] = useState(false);
useEffect(() => {
console.log(db);
}, []);
return (
<>
<div className="container">
<div className="container-md">
<div className="faq">
<img src={bg} className="bg" />
<img src={bg1} className="bg1" />
<img src={bg2} className="bg2" />
<div className="card">
<h1>FAQ</h1>
<div className="info">
{db.map((dat) => (
<Faq
toggle={toggle}
setToggle={setToggle}
title={dat.title}
desc={dat.desc}
key={dat.id}
id={dat.id}
/>
))}
</div>
</div>
</div>
</div>
</div>
</>
);
}
export default App;
(map coming from simple data.js file that I created. it includes just id title desc.)
Faq.js
import React from "react";
import arrow from "./images/icon-arrow-down.svg";
const Faq = ({ toggle, setToggle, title, desc, id }) => {
return (
<>
{" "}
<div className="question" onClick={() => setToggle(!toggle)}>
<p>{title}</p>
<img src={arrow} className={toggle ? "ikon aktif" : "ikon"} />
</div>
<p className="answer border">{toggle ? <>{desc}</> : ""}</p>
</>
);
};
export default Faq;
You need to store the index value of the toggle item.
You can modify the code with only 2 lines with the existing codebase.
import "./App.css";
import React, { useState, useEffect } from "react";
import bg from "./images/bg-pattern-desktop.svg";
import bg1 from "./images/illustration-box-desktop.svg";
import bg2 from "./images/illustration-woman-online-desktop.svg";
import { data } from "./data";
import Faq from "./Faq";
function App() {
const [db, setDb] = useState(data);
const [toggle, setToggle] = useState(-1); //Modify Here
useEffect(() => {
console.log(db);
}, []);
return (
<>
<div className="container">
<div className="container-md">
<div className="faq">
<img src={bg} className="bg" />
<img src={bg1} className="bg1" />
<img src={bg2} className="bg2" />
<div className="card">
<h1>FAQ</h1>
<div className="info">
{db.map((dat, index) => ( //Modify Here
<Faq
toggle={index === toggle} //Modify Here
setToggle={() => setToggle(index)} //Modify Here
title={dat.title}
desc={dat.desc}
key={dat.id}
id={dat.id}
/>
))}
</div>
</div>
</div>
</div>
</div>
</>
);
}
export default App;
import React from "react";
import arrow from "./images/icon-arrow-down.svg";
const Faq = ({ toggle, setToggle, title, desc, id }) => {
return (
<>
{" "}
<div className="question" onClick={setToggle}>
<p>{title}</p>
<img src={arrow} className={toggle ? "ikon aktif" : "ikon"} />
</div>
<p className="answer border">{toggle ? <>{desc}</> : ""}</p>
</>
);
};
export default Faq;
You will need state for each toggle. Here is a minimal verifiable example. Run the code below and click ⭕️ to toggle an item open. Click ❌ to close it.
function App({ faq = [] }) {
const [toggles, setToggles] = React.useState({})
const getToggle = key =>
Boolean(toggles[key])
const setToggle = key => event =>
setToggles({...toggles, [key]: !getToggle(key) })
return faq.map((props, key) =>
<Faq key={key} {...props} open={getToggle(key)} toggle={setToggle(key)} />
)
}
function Faq({ question, answer, open, toggle }) {
return <div>
<p>
{question}
<button onClick={toggle} children={open ? "❌" : "⭕️"} />
</p>
{open && <p>{answer}</p>}
</div>
}
const faq = [
{question: "hello", answer: "world"},
{question: "eat", answer: "vegetables"}
]
ReactDOM.render(<App faq={faq} />, document.querySelector("#app"))
p { border: 1px solid gray; padding: 0.5rem; }
p ~ p { margin-top: -1rem; }
button { float: right; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Instead of doing this (in App component):
const [db, setDb] = useState(data);
const [toggle, setToggle] = useState(false);
you can write an useState hook like below to combine the two hooks and assign an isOpened property for each Faq element:
const [db, setDb] = useState(data.map(value=>{return {...value, isOpened:false}}));
and then right here you can do this (as the child of <div className="info">):
{db.map((dat, index) => (
<Faq
toggle={dat.isOpened}
setToggle={() => toggleById(dat.id)}
title={dat.title}
desc={dat.desc}
key={dat.id}
id={dat.id}
/>
))}
Also you need to declare toggleById function in App component:
const toggleById = (id) => {
const newDb = db.map(dat=>{
if(dat.id==id){
return {...dat,isOpened:!dat.isOpened}
}
return dat;
});
setDb(newDb);
}
and since setToggle prop of Faq, calls toggleById by its defined parameter, there is no need to do this in Faq component:
<div className="question" onClick={() => setToggle(!toggle)}>
you can simply write:
<div className="question" onClick={setToggle}>

Why when passing parameters from one component to another it arrives undefined and then arrives again with the data?

As will be shown below when passing properties from a parent component to a child component my code is executed first before the properties arrive and when trying to do a .map of an Array it returns the error "Cannot read properties of undefined (reading 'map')". Why does this happen?
As you can see in the image, first you get undefined values which generates the error in the .map and then you get the properties
Parent component:
import React, {useEffect, useState} from "react";
import ItemDetail from "./itemDetail";
import '../../App.css';
import { useParams } from "react-router-dom";
//Component Class
const ItemDetailContainer = () => {
const [producto, productos] = useState([]);
const { productId } = useParams();
useEffect(() => {
fetch('http://localhost:3000/productos/' + productId)
.then(res=>res.json())
.then(data=>productos(data))
}, [productId]);
console.log(producto);
return (
<div className="container">
<ItemDetail
nombre={producto.nombre}
id={producto.id}
precio={producto.precio}
category={producto.category}
imagenes={producto.imagenes}
ancho={producto.ancho}
alto={producto.alto} />
</div>
)
}
export default ItemDetailContainer;
Child component:
import React from 'react';
import { Card } from 'react-bootstrap';
import ItemCount from '../itemCount';
const ItemDetail = ({ nombre, id, precio, category, imagenes, ancho, alto }) => {
console.log(imagenes);
return (
<div className="row" key={id} id={id}>
<div className="col-md-6" id="productImage">
<div className="carousel-item">
{imagenes.map((p) => (
<img src={p} className="d-block w-100" alt={nombre} />
))}
</div>
</div>
<div className="col-md-6 producto">
<div className="card">
<Card.Body>
<Card.Title>{nombre}</Card.Title>
<Card.Text>{category}</Card.Text>
<Card.Text>${precio}</Card.Text>
<ItemCount />
</Card.Body>
</div>
</div>
</div>
);
};
export default ItemDetail;
Change your code to only execute if imagenes is an array. Personally I would rethink how you are structuring your initial state. Instead of it being an empty array, perhaps make it an object with all of those properties having default values.
<div className="carousel-item">
{ Array.isArray(imagenes) && imagenes.map((p) => (
<img src={p} className="d-block w-100" alt={nombre} />
))}
</div>

variable name of src parameter of image in React

How can I define src parameter in React jsx imgage tag? I map an array and I need define src parameter depends on index of array.
import leaf1 from "../../assets/menu-clip/leafes/leaf1.png";
import leaf2 from "../../assets/menu-clip/leafes/leaf2.png";
import leaf3 from "../../assets/menu-clip/leafes/leaf3.png";
import leaf4 from "../../assets/menu-clip/leafes/leaf4.png";
import leaf5 from "../../assets/menu-clip/leafes/leaf5.png";
export default function Menu(props) {
const menuList = props.menu.menuList;
return (
<div className={styles.menuContainer}>
<ul className={styles.list}>
{menuList.map( (m,i) => (
<li className={styles.menuLi}
key={i}>
{m.name}
<img src={ **leaf + (i+1)** } // ???????
alt="menu lístok"
width="50"/>
</li>
)
)}
</ul>
</div>
)
}
You could store it in a array and reference that
like
const leafs = [leaf1,leaf2,...]
//then
src={leafs[i+1]}
import leaf1 from "../../assets/menu-clip/leafes/leaf1.png";
import leaf2 from "../../assets/menu-clip/leafes/leaf2.png";
import leaf3 from "../../assets/menu-clip/leafes/leaf3.png";
import leaf4 from "../../assets/menu-clip/leafes/leaf4.png";
import leaf5 from "../../assets/menu-clip/leafes/leaf5.png";
export default function Menu(props) {
const menuList = props.menu.menuList;
const leafArray = [leaf1, leaf2, leaf3, leaf4, leaf5];
return (
<div className={styles.menuContainer}>
<ul className={styles.list}>
{
menuList.map( (m,i) => (
<li className={styles.menuLi}
key={i}>
{m.name}
<img src={ leafArray[i] }
alt="menu lístok"
width="50"/>
</li>
))
}
</ul>
</div>
)
}

How to call an action from a component without connecting it to the redux store?

I have a Cards component which takes in the props from the UserPostscomponent(which is connected to the store) and displays cards. Cards is not connected to the redux store and I want to dispatch an action in the handleDelete function. How can I do that?
import React, { Component } from "react"
class Cards extends Component {
handleDelete = (id) => {
}
render() {
const { title, description } = this.props.post
const { postId } = this.props.post._id
return (
<div className="card">
<div className="card-content">
<div className="media">
<div className="media-left">
<figure className="image is-48x48">
<img
src="https://bulma.io/images/placeholders/96x96.png"
alt="Placeholder image"
/>
</figure>
</div>
<div className="media-content" style={{border: "1px grey"}}>
<p className="title is-5">{title}</p>
<p className="content">{description}</p>
<button className="button is-success">Edit</button>
<button onClick={this.handleDelete(postId)} className="button is-success">Delete</button>
</div>
</div>
</div>
</div>
)
}
}
export default Cards
UserPosts component which passes the props
<div>
{userPosts &&
userPosts.map(post => {
return <Cards key={post._id} post={post} />
})}
</div>
```
You can use the global store and directly call dispatch method. Not recommended. Hard to maintain and debug.
import { createStore } from 'redux'
const store = createStore(todos, ['Use Redux'])
// Dont create new one, use the one created in root
function addTodo(text) {
return {
type: 'ADD_TODO',
text
}
}
store.dispatch(addTodo('Read the docs'))
store.dispatch(addTodo('Read about the middleware'))

React: Append Components to the DOM

I am rendering components in React by mapping through a JSON object. I now want to append these components to the dom. How can I select each of these components and append them to the DOM?
All of the usual jQuery methods are not working.
{dataobj.items.map( (instance) => {
return (
<div key={instance.title} className="new">
<Event time={parseInt(instance.start_time)} title={instance.title} start_time={instance.start_time} location={instance.location} />
</div>
)
})}
import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import moment from 'moment';
import Event from './Event.jsx';
const classNames = require('classnames');
const ReactDOM = require('react-dom')
export default class Calendar extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
ReactDOM.findDOMNode(this)
console.log(this);
$('#nine').append($('new'))
}
render() {
var timeStamp = function() {
var datafile = require("json!./data.json");
{datafile.items.map(function(instance) {
const timeElement= parseInt(instance.start_time);
console.log(timeElement);
return timeElement
})}
}
var dataobj = require("json!./data.json");
return (
<div className="calendar">
<div className="amContainer">
<div className="amSide">AM</div>
<div className="linesContainer">
<div className="hourBlock">
<div id="nine" className="time">
</div>
<div className="halfHour">
{moment().format('9:30')}
</div>
</div>
<div className="hourBlock">
<div className="time">
{moment().format('10:00')}
</div>
<div className="halfHour">
{moment().format('10:30')}
</div>
</div>
<div className="hourBlock">
<div className="time">
{moment().format('11:00')}
</div>
<div className="halfHour">
{moment().format('11:30')}
</div>
</div>
</div>
</div>
{dataobj.items.map( (instance) => {
return (
<div key={instance.title} className="new">
<Event time={parseInt(instance.start_time)} title={instance.title} start_time={instance.start_time} location={instance.location} />
</div>
)
})}
</div>
);
}
}
First, you need to adjust your render method. You need to map over the dataObject, set it to a variable, in this case I call it objects and then use that in the jsx you already have as {objects} as a child like so:
render() {
// your render logic
var objects = dataobj.items.map( (instance) => {
return (
<div key={instance.title} className="new">
<Event
time={parseInt(instance.start_time)}
title={instance.title}
start_time={instance.start_time}
location={instance.location}
/>
</div>
)
return (
<ExampleComponent>
// your main html should go here this is just a simple example
{objects}
<ExampleComponent/>
)
}

Categories