Pass Images url using props - javascript

I'm trying to send with props some icons between two components. I import the urls and I'm using it to do the prop object.
This is my main file.
import { useState } from 'react';
import SapIcon from '../images/logo_sap.png';
import ExcelIcon from '../images/logo_excel.png';
import OutlookIcon from '../images/logo_outlook.png';
import BrowserIcon from '../images/logo_webbrowser.png';
import OneDriveIcon from '../images/logo_onedrive.png';
import XhisIcon from '../images/logo_xhis.png';
import LeftBlock from './LeftBlock';
const BotsGrid = () => {
const [icons, setIcons] = useState([{
SapIcon: { SapIcon },
ExcelIcon: { ExcelIcon },
OutlookIcon: { OutlookIcon },
BrowserIcon: { BrowserIcon },
OneDriveIcon: { OneDriveIcon },
XhisIcon: { XhisIcon }
}]);
console.log(icons.SapIcon);
return (
<div className='BotsGrid'>
<div class="site-section bg-light">
<div class="container">
<LeftBlock icons={icons} />
</div>
</div>
</div>
);
}
export default BotsGrid;
I try to import this prop on my LeftBlock.js file but this doesn't work
const LeftBlock = (props) => {
const icons = props.icons;
return (
<div className="LeftBlock">
<div class="row">
<div class="col-lg-6">
<div class="d-flex tutorial-item mb-4">
<div class="container">
<h3>Test</h3>
<img src={ icons.SapIcon } alt="Image" width="12%" height="12%" class='mr-4'/>
<img src={ icons.ExcelIcon } alt="Image" width="8%" height="8%" class='mr-4' />
<img src={ icons.OutlookIcon } alt="Image" width="8%" height="8%" class='mr-4' />
</p>
<p class="meta">
<span class="mr-2 mb-2">Business</span>
</p>
<p>Details</p>
</div>
</div>
I need some help because the page doesn't show the icons.

you are using an array just remove it
const BotsGrid = () => {
const [icons, setIcons] = useState({
SapIcon: SapIcon ,
ExcelIcon: ExcelIcon,
OutlookIcon: OutlookIcon ,
BrowserIcon: BrowserIcon,
OneDriveIcon: OneDriveIcon,
XhisIcon: XhisIcon
});

Related

Show post content in the same page ReactJS

i'm creating a blog. in my index.js i have a left sidebar that shows the article links.
What I'm trying to do is when I click on the link the post content should be shown in the right sidebar of my index.js
At the moment it's been opened in a new page.
index.js
const IndexPage = ({
data: {
allMarkdownRemark: { edges },
},
}) => {
const PostData = edges[0]
const Posts = edges
.filter(edge => !!edge.node.frontmatter.date) // You can filter your posts based on some criteria
.map(edge => <PostLink key={edge.node.id} post={edge.node} />)
return (
<div className='html-container'>
<div className='main-container'>
<div className='row'>
<div className='left-sidebar'>
<div className='logo'>
<p>logo</p>
</div>
<div className='menu'>
{Posts}
</div>
<div className='social'>
<img src={twitch} />
<img src={discord} />
<img src={twitter} />
<img src={email} />
</div>
</div>
<div className='right-sidebar'>
</div>
</div>
</div>
</div>
)
}
post-link.js
import React from "react"
import { Link } from "gatsby"
const PostLink = ({ post }) => (
<div>
<Link to={"/blog"+post.frontmatter.slug}>
{post.frontmatter.title}
{/* {post.frontmatter.title} ({post.frontmatter.date}) */}
</Link>
</div>
)
export default PostLink
Check the API of the Link and if it has an equivalent of target attribute.

Showing Item details in Reactjs component using Laravel API

I have a list of fruits I want show their details. I have built the cards to display the list, and now I want to build a page that shows details for every item and open up its corresponding card list is clicked. I keep getting an error
TypeError: Cannot read properties of undefined (reading 'name')
The list cards work fine, and the individual item api also works fine. But now I cant display the details. Kindly help.
The Card Component
import React from 'react';
import { Link } from "react-router-dom";
import { LazyLoadImage } from "react-lazy-load-image-component";
const FruitWidget = ({ fruit }) => {
return (
<div className="col-6">
<div className="card mb-2">
<Link to={"/fruit-details/"+fruit.id}>
<LazyLoadImage src="assets/img/sample/photo/product1.jpg"
className="card-img-top lazycolor" alt="image" />
<div className="card-body">
<h4 className="mb-0">{fruit.name}</h4>
</div>
</Link>
</div>
</div>
);
}
export default FruitWidget;
The Items List
import React, { useState, useEffect } from 'react';
import { useNavigate } from "react-router-dom";
import Menubar from "../../components/menubar/Menubar"
import FruitWidget from "../../components/widgets/FruitWidget"
import { LazyLoadImage } from "react-lazy-load-image-component";
import WidgetSkeleton from "../../components/skeleton/WidgetSkeleton"
function Training() {
let navigate = useNavigate();
const [fruits, setFruits] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch("http://localhost:8000/api/fruits")
.then((result) => result.json())
.then((fruits) => {
setFruits(fruits);
setIsLoading(false);
});
}, []);
console.warn("result", fruits)
return (
<div className="section">
<div className="row">
{isLoading && <WidgetSkeleton cards={6} />}
{fruits.map((fruit) => (
<FruitWidget fruit={fruit} key={fruit.id} />
))}
</div>
</div>
);
}
export default Training;
The Details Component
import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from "react-router-dom";
import Menubar from "../../components/menubar/Menubar"
import Tabs from "../../components/fruittabs/FruitTabs";
function FruitDetails() {
let navigate = useNavigate();
const [fruit, setFruit] = useState({});
const { fruitId } = useParams();
useEffect(() => {
fetch(`http://localhost:8000/api/fruit/${fruitId}`)
.then((result) => result.json())
.then((fruit) => {
setFruit(fruit[0]);
});
}, [fruitId]);
return (
<div>
<Menubar />
<div className="appHeader bg-primary text-light">
<div className="left">
<a onClick={() => navigate(-1)} className="headerButton goBack">
<i className="fi fi-rr-angle-left"></i> </a>
</div>
<div className="pageTitle">{fruit.name}</div>
<div className="right"></div>
</div>
<div id="appCapsule">
<div className="section mt-3 mb-3">
<img src="assets/img/lazyload.svg"
alt="image" className="imaged img-fluid fruit-detail-main" />
</div>
<div className="section mt-3 mb-3">
<div>
<Tabs>
<div label="Details">
{fruit.details}
</div>
<div label="Infestations">
After 'while, <em>Crocodile</em>!
</div>
<div label="Advice">
Nothing to see here, this tab is <em>extinct</em>!
</div>
</Tabs>
</div>
</div>
</div>
</div>
);
}
export default FruitDetails;

How to transfer image and data between components | React

In the project I have a Upload image component that asks the user for an image and then previews it on the page. The image is not persay "uploaded" to any server and I hope that it does'nt need to. The goal is to be able to compare this uploded image with a random active set of images from an API (Image.js). What I have problem with is how to use the previewImage: URL.createObjectURL(event.target.files[0]) inside of another file, or at least that is what I belive to be the right way to think about it. (For context: The idea is to check the correlation between the uploaded file and the random active set.)
I have tried to implement an child to child state transfer but gave up when it did not work for the child to parent part. App.js is the parent, Image.js and image-upload.component.js are the children. I have also looked for ways to solve this with redux but don't understand how to store images or utilize states inside of the store. For this i only need to update the image state when files are selected by user.
To somewhat summarize and clarify the question: How can I transfer the chosen image file between two components and use the data in both of them?
This is my first project in React so the code may be caotic and full of "brute force" so I apologice in advance for that. Any help or guidence is greatly appreciated!
App.js:
import React from "react";
import "./App.css";
import Navbar from './components/Navbar/Navbar'
import "bootstrap/dist/css/bootstrap.min.css";
import UploadImages from "./components/image-upload.component";
import Images from "./components/Images";
function App() {
return (
<div className="App">
<Navbar />
<div className="container">
<div className="row">
<div className="col-5">
<div className="content">
<h3>Title</h3>
<h4>Upload my picture here</h4>
<UploadImages/>
</div>
</div>
<div className="col-2">
</div>
<div className="col-5">
<Images />
</div>
</div>
</div>
</div>
);
}
export default App;
Images.js (pure, brute force code i guess):
import UploadImages from "./image-upload.component";
import React, {useEffect, useState} from "react";
import "./Images.css";
function shuffleArray(array) {
let i = array.length - 1;
for (; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function Images() {
const [urls, setURLs] = useState([]);
const [count, setCount] =useState(0)
useEffect(() => {
const urls = [
250940,
20622,
436625,
436444,
436509,
359245,
459090,
333933,
333916,
466350,
44831,
383010,
202660,
406317,
337349,
503448,
12617,
248662,
435805,
438545
].map(
(itemId) =>
`https://collectionapi.metmuseum.org/public/collection/v1/objects/${itemId}`
);
shuffleArray(urls)
Promise.all(
urls.map((currUrl) =>
fetch(currUrl)
.then((response) => response.json())
.then((data) => data.primaryImage)
.catch((error) => console.log("There was a problem!", error))
)
).then((fetchedUrls) => setURLs(fetchedUrls));
}, []);
if (count === 3) {
return (
<div>
<div class="imageContainer">
<div class="images__item">
<img class="photo" src={urls[1]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[2]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[3]} alt="" />
</div>
</div>
<button
onClick={() => setCount(4)}>
Next
</button>
</div>
)
}
if (count === 4) {
return (
<div>
<div class="imageContainer">
<div class="images__item">
<img class="photo" src={urls[1]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[2]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[3]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[4]} alt="" />
</div>
</div>
<button
onClick={() => setCount(3)}>
Previous
</button>
<button
onClick={() => setCount(5)}>
Next
</button>
</div>
)
}
if (count === 5) {
return (
<div>
<div class="imageContainer">
<div class="images__item">
<img class="photo" src={urls[1]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[2]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[3]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[4]} alt="" />
</div>
<div class="images__item">
<img class="photo" src={urls[5]} alt="" />
</div>
</div>
<button
onClick={() => setCount(4)}>
Previous
</button>
<button
onClick={() => {setCount(3); shuffleArray(urls);}}>
Reset
</button>
</div>
)
}
else {
return (
<div>
{/* <UploadImages upsideEmit={getStateFromChild} /> */}
<button
onClick={() => {shuffleArray(urls); setCount(3);}}>
Open
</button>
</div>
);
}
}
export default Images;
image-upload.component.js:
import React, { Component } from "react";
import UploadService from "../services/file-upload.service";
import "./Images"
class UploadImages extends Component {
constructor(props) {
super(props);
this.selectFile = this.selectFile.bind(this);
this.upload = this.upload.bind(this);
this.state = {
currentFile: undefined,
previewImage: undefined,
progress: 0,
message: "",
imageInfos: [],
};
}
componentDidMount() {
UploadService.getFiles().then((response) => {
this.setState({
imageInfos: response.data,
});
});
}
selectFile(event) {
this.setState({
currentFile: event.target.files[0],
previewImage: URL.createObjectURL(event.target.files[0]),
message: ""
});
}
upload() {
this.setState({
progress: 0,
});
UploadService.upload(this.state.currentFile, (files) => {
this.setState({
imageInfos: files.data,
});
})
}
render() {
const {
previewImage,
} = this.state;
return (
<div>
<div className="row">
<div className="col-8">
<label className="btn btn-default p-0">
<input type="file" accept="image/*" onChange={this.selectFile} />
</label>
</div>
<div className="col-4">
</div>
</div>
{previewImage && (
<div>
<img className="preview" src={previewImage} alt="" />
</div>
)}
</div>
);
}
}
export default UploadImages
In general you would want to useContext hook for this.
Check out this tutorial https://dev.to/email2vimalraj/react-hooks-lift-up--pass-down-state-using-usecontext-and-usereducer-5ai0

How do I only show render when the render has completed in React?

Hope this doesn't sound like a stupid question, but all queries I've searched on here and Google ask about only showing the render once fetches/requests have completed.
I want my React app to only show the render once the render has completed, including the CSS. At the moment, in a fraction of a second, you can see the page being built - in under a split second, but still it's not a fluid flow for the UX. Is there a way to only load the page once the render (including the CSS) is all done? I don't want to do a setTimeout with a loading page as that is very clunky.
Many thanks in advance
Code below:
import React, { useEffect, useContext } from 'react';
import { NavLink } from 'react-router-dom';
import axios from 'axios';
import '../../styles/MleaveReqUpper.css';
// import '../../styles/leaveRequests.css';
import leftArrow from '../../img/general/leftArrow.svg';
import teamsGrad from '../../img/general/teamsGrad.png';
import returnBack from '../../img/general/returnBack.svg';
import cog from '../../img/general/cog.svg';
import checklist from '../../img/general/checklist.svg';
import { DataContext } from '../../contexts/DataContext';
import $ from 'jquery';
import requestsSelected from '../../img/mFooter/requestsSelected.svg';
const MLeaveReqUpperLinks = () => {
const { teamAllows, toggleTeamAllows } = useContext(DataContext);
const navBlue = () => {
$('.f3').attr('src', requestsSelected);
};
useEffect(() => {
axios.get('db.json').then();
});
// render
return (
<div className='leaveReqUpperContainer'>
<img className='teamGradientOut' src={teamsGrad} />
<NavLink to='/requests'>
<div
className='backGroup'
onClick={() => {
navBlue();
if (teamAllows) {
toggleTeamAllows(false);
}
}}
>
<img
className='returnBack'
src={returnBack}
alt='Back to My Requests'
/>
</div>
</NavLink>
<h3 className='TeamRequests'>Team Requests</h3>
<div className='iconsM'>
<NavLink to='team-allowances'>
<img
onClick={() => {
toggleTeamAllows();
}}
className={`checklist ${!!teamAllows ? 'iconSelected' : ''}`}
src={checklist}
alt='Allowances'
/>
</NavLink>
<img className='cog' src={cog} alt='Settings' />
</div>
<div className='teamsXbar'>
<div className='teamsInnerContainer'>
<div className='teamMenuHolder'>
<p className='teamName teamSel '>All Staff</p>
</div>
<div className='teamMenuHolder'>
<p className='teamName'>Brewery</p>
</div>
<div className='teamMenuHolder'>
<p className='teamName'>Sales</p>
</div>
<div className='teamMenuHolder'>
<p className='teamName'>Finance</p>
</div>
<div className='teamMenuHolder'>
<p className='teamName'>Operations</p>
</div>
<div className='teamMenuHolder'>
<p className='teamName'>Marketing</p>
</div>
</div>
</div>
</div>
);
};
export default MLeaveReqUpperLinks;
You can use a loading state variable
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
setIsLoading(true);
axios.get('db.json').then(res=>setIsLoading(false););
});
return isLoading ? null : <div>All your view</div>

ReactJs Cannot read property 'props' of undefined

I have react js code of inner most child component like this
import React from 'react'
import { addToCart } from 'actions/cart'
export default (props) => {
const { line_item, cart} = props
// const oClick = line_item.oClick.bind(line_item)
const handleClick = (id) => this.props.dispatch(addToCart(id, 1))
// *I am getting error above line*
return (
<div>
<ul className="ul-reset">
<li>
<div className="cart-prod-wrapper cf">
<div className="cart-image-wrapper">
<div className="cart-image">
<a href="#"><img src="#" alt="Product One"/>
</a>
</div>
</div>
<div className="cart-details">
<div className="cart-name">
{line_item.variant.name}
</div>
<div className="cart-price">{line_item.variant.price}</div>
</div>
<div className="cart-qty">
<div className="cart-qty-name">QTY:</div>
<div className="cart-qty-value">
<div class="minus"><span>-</span></div>
{line_item.quantity}
<div class="plus">
<span value = { line_item.variant.id } onClick={handleClick(line_item.variant.id)} >+</span></div>
</div>
</div>
<div className="cart-total">
<div className="cart-total-name">Total</div>
<div className="cart-total-value">{line_item.variant.price * line_item.quantity}</div>
</div>
</div>
</li>
</ul>
</div>
)
}
i want to perform to call an action using dispatch
and code of parent presentation component is line
export default (props) => {
const { account, cart, readMore1} = props
return (
<li>
{ !cart.isFetching && cart.line_items.map(
(line_item, i) => <CartPreview key = {i} line_item= {line_item} cart ={cart} />)
}
</li>
)
}
can any on please guide me to solve this error
Edit
const mapStateToProps = (state) => {
return {
account: getAccount(state),
cart: getCart(state),
classToSend: getReadmore(state),
authenticityToken: getAuthenticityToken(state)
}
}
export default connect(mapStateToProps)(HeaderContainer)
May be this could help
import React from 'react'
import { connect } from 'react-redux' // import connect from redux
import { addToCart } from 'actions/cart'
// name component to wrap it with connect
const MyComponent = (props) => {
const { line_item, cart} = props
return (
<div>
<ul className="ul-reset">
<li>
<div className="cart-prod-wrapper cf">
<div className="cart-image-wrapper">
<div className="cart-image">
<a href="#"><img src="#" alt="Product One"/>
</a>
</div>
</div>
<div className="cart-details">
<div className="cart-name">
{line_item.variant.name}
</div>
<div className="cart-price">{line_item.variant.price}</div>
</div>
<div className="cart-qty">
<div className="cart-qty-name">QTY:</div>
<div className="cart-qty-value">
<div class="minus"><span>-</span></div>
{line_item.quantity}
<div class="plus">
// used arrow function
<span value = { line_item.variant.id } onClick={() => props.dispatch(addToCart(line_item.variant.id, 1)} >+</span></div>
</div>
</div>
<div className="cart-total">
<div className="cart-total-name">Total</div>
<div className="cart-total-value">{line_item.variant.price * line_item.quantity}</div>
</div>
</div>
</li>
</ul>
</div>
)
}
export default connect()(MyComponent); // connect dispatch to component

Categories

Resources