ReactJS - Local Image not showing - javascript

I have image paths in an array and I want to display the images when I map the array. My code is as follows :
import React, { Component } from 'react';
class ItemsList extends Component {
constructor() {
super();
this.state = {
products: [
{
"name": "Item 1",
"imageURL": "../images/milk.jpg"
},
{
"name": "Item 2",
"imageURL": "../images/bread.jpg"
},
]
}
}
render() {
const { products } = this.state;
return (
<div>
<div className="row">
{
products.map((val, ind) => {
return (
<div className="card mx-2 my-2 shadow-lg p-3 mb-5 bg-white rounded" key={ind} style={{ width: '345px', alignItems: 'center' }}>
<img src={val.imageURL} className="card-img-top" style={{ height: '240px', width: '240px' }} alt="product image" /> // *** Displaying Image Here ***
<div className="card-body" style={{ backgroundColor: '#a6b0bf', width: '100%', textAlign: 'center' }}>
<h5 className="card-title">{val.name}</h5>
<br />
</div>
</div>
);
})
}
</div>
</div>
);
}
}
export default ItemsList;
The image is not displaying. I want to display the image in the map method but can't get it done. Need help.

You may need to use require:
<img src={require(`${val.imageURL}`)} className="card-img-top" />

Related

Css cards carousel scrollTo not aligning on multiple clicks

I'm trying to implement the card carousel using react, on clicking the next and previous buttons I'm able to scroll to the next and previous cards, and works fine. when I fast-click multiple times on the next or prev buttons it's messing up the alignment of cards.
import React, { useRef } from "react";
import Card from "./card";
import "./App.scss";
// import "./";
// import leftCircle from "./asset/leftarrow.svg";
// import rightCircle from "./asset/img_92071.png";
const CardArray = [
{ name: "first card" },
{ name: "second card" },
{ name: "third card" },
{ name: "fourth card" },
{ name: "fifth card" },
{ name: "sixth card" },
{ name: "seventh card" },
{ name: "seventh card" },
{ name: "seventh card" },
{ name: "seventh card" }
];
function App() {
let carouslRef = useRef(null);
const prev = () => {
carouslRef &&
carouslRef.current &&
carouslRef.current.scrollTo({
behavior: "smooth",
top: 0,
left: carouslRef.current.scrollLeft - 210
});
console.log(carouslRef.current.scrollLeft, carouslRef.current.clientWidth);
};
const next = () => {
carouslRef &&
carouslRef.current &&
carouslRef.current.scrollTo({
behavior: "smooth",
top: 0,
left: carouslRef.current.scrollLeft + 210
// carouslRef.current.scrollLeft + carouslRef.current.clientWidth,
});
console.log(carouslRef.current.scrollLeft, carouslRef.current.clientWidth);
};
return (
<div className="carousel">
<button className="direction" onClick={prev}>
{/* <img className="arrow" src={leftCircle} alt="left button" /> */}
<div
className="arrow"
// style={{ width: "20px", height: "20px", backgroundColor: "red" }}
></div>
</button>
<div className="card-div">
<main className="card-scroll" ref={carouslRef}>
{CardArray.map((carousel, i) => (
<Card {...carousel} key={i} />
))}
</main>
</div>
<button className="direction" onClick={next}>
{/* <img className="arrow" src={rightCircle} alt="right button" /> */}
<div
className="arrow"
// style={{ width: "20px", height: "20px", backgroundColor: "red" }}
>
next
</div>
</button>
</div>
);
}
export default App;
you can see the full code and output with this react CodeSandbox URL: https://codesandbox.io/s/gallant-voice-eh5v6p?file=/src/App.js

Image not displaying in React

I'm having an issue getting an image to appear within my React project. I've done it before and actually copied the same exact code to put it into my project, but for some reason nothing is showing up. I looked in the console and inspected the image and it's showing that there is something there, but just not rendering somehow. Nothing I search for online has a similar issue so I'm wondering if I'm just missing something, and that's what causing it not to render.
Here is the parts of my file that pertains to my question.
import React from 'react';
import { Link } from 'react-router-dom';
import Button from '../../components/Spinner/Button';
import ATABanner from '../../../public/Images/ATAbanner-flip.png';
import ATADouble from '../../../public/Images/ATAdouble-1.png';
import ATASingle from '../../../public/Images/ATAsingle-1.png';
import '../../StyleSheets/AdContract.css';
import '../../StyleSheets/Button.css';
export default class CustomerPage extends React.Component{
constructor(props){
super(props);
this.state = {
QuoteID: this.props.match.params.id,
CustomerFirst: "",
CustomerLast: "",
CurrStep: 1,
StoreList: [],
StoresSelected: [],
AdSize: "",
AdSelected: "",
}
}
... extra stuff and methods here
AdSizeHandler(e){
console.log(e.target.id);
switch(e.target.id){
case "SINGLE": this.setState({AdSize: e.target.id});
break;
case "DOUBLE": this.setState({AdSize: e.target.id});
break;
case "BANNER": this.setState({AdSize: e.target.id});
break;
}
}
RenderAdSelected(){
let img = null;
let ad = this.state.AdSize;
if(ad == "SINGLE"){
img = (
<img id="ad-image-single" name='ADSingle' src={ATASingle} alt="" width="100%" scrolling="no"/>
)
}else if(ad == "DOUBLE"){
img = (
<img id="ad-image-double" name='ADDouble' src={ATADouble} alt="" width="100%" scrolling="no"/>
)
}else if(ad == "BANNER"){
img = (
<img id="ad-image-banner" name='ADBanner' src={ATABanner} alt="" width="100%" scrolling="no"/>
)
}
return img;
}
render(){
return(
<div id="CustomerContainer" style={{width: '100%', height: '100%'}}>
<div id="CustomerContent" className="fade-in" style={{textAlign: 'center', width: '100%', height: '100%', overflowY: 'auto'}}>
<div id="Welcome" style={{marginTop: '5%'}}>
<p style={{fontSize: '35px', fontWeight: 'bold'}}>Hello, {this.state.CustomerFirst + " " + this.state.CustomerLast}</p>
<p style={{fontSize: '20px', color: 'orange'}}><b>Your Quote Is Almost Ready!</b></p>
</div>
<div style={{marginTop: '5%', color: '#0F9D58', fontSize: '37px'}}>
<p><b>Step: {this.state.CurrStep}</b></p>
</div>
<div id="InnerContainer" style={{width: '80%', marginLeft: 'auto', marginRight: 'auto'}}>
{this.RenderStoreSelect(this.state.CurrStep)}
<div id="ad-select">
<div className="fade-in" id="ad-prompt">
<p style={{fontSize: '20px'}}><b>Please Select Your Ad Size</b></p>
</div>
<div id="ad-buttons" style={{display: 'inline-block', marginTop: '2%'}}>
<span style={{display: 'flex'}}>
<Button name="SINGLE" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
<Button name="DOUBLE" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
<Button name="BANNER" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
</span>
</div>
<div>
<img id="adImage" name='ADSingle' src={ATASingle} alt="" width="100" height="100"/>
</div>
</div>
</div>
{this.ConfirmQuote()}
</div>
</div>
)
}
}
Here is proof that it's retrieving the image:
If anyone has any idea what I'm possibly doing wrong, please let me know. Thanks.
I found out the reason for this issue. The problem is that I am in a different route than the home route '/'. I solved my problem by doing this instead: <img id="adImage" name='ADSingle' src={`/${ATASingle}`} alt="" width="100" height="100"/>

React - onSubmit form without any data

I put a submit test button but its not getting any data.
OBS about the code:
I'm using react select
I'm using filepond to upload images and files (its working fine)
ProductsModal is a modal component with rightColumn and leftColumn (left column is the form and right column there is a phone image with dynamic content inside which is a preview of the form.
My onSubmit function is a console.log with data from the form, but all I get is a empty object.
I have the following code
import React, { useState } from 'react'
import useForm from 'react-hook-form'
import Select from 'react-select'
import { FaRegFileAlt, FaRegImage } from 'react-icons/fa'
import { FilePond, registerPlugin } from 'react-filepond'
import { IoIosImages } from 'react-icons/io'
import FilePondPluginImageExifOrientation from 'filepond-plugin-image-exif-orientation'
import FilePondPluginImagePreview from 'filepond-plugin-image-preview'
import TextField from '#material-ui/core/TextField'
import Button from '~/components/Button'
import ProductsModal from '~/components/Sponsor/Modals/ProductsModal'
import IconsProductImage from '~/components/Sponsor/IconsProductImage'
import Border from '~/components/Border'
import ProductBadge from '~/components/ProductBadge'
import * as S from './styled'
registerPlugin(FilePondPluginImageExifOrientation, FilePondPluginImagePreview)
export default function ModalAnnouncement({ handleCloseModal, showModal }) {
const [title, setTitle] = useState('')
const [tags, setTags] = useState([])
const [about, setAbout] = useState('')
const [files, setFiles] = useState('')
const [filePreview, setFilePreview] = useState('')
const [images, setImages] = useState('')
const [updatingFile, setUpdatingFile] = useState(false)
const [updatingImage, setUpdatingImage] = useState(false)
const { handleSubmit, setValue } = useForm()
function onSubmit(data) {
console.log('data', data)
}
function handleUpdatingFile() {
setUpdatingFile(!updatingFile)
}
function handleUpdatingImage() {
setUpdatingImage(!updatingImage)
}
function handleUpdateImages(event) {
setImages(event)
setFilePreview(event.length === 0 ? '' : URL.createObjectURL(event[0].file))
}
function handleTagsChange(tags) {
setValue('tags', tags)
setTags(tags)
}
const tagsAvailable = [
{ value: 1, label: 'artificial intelligence' },
{ value: 2, label: 'digital marketing' },
{ value: 3, label: 'big data' },
{ value: 4, label: 'blogging' },
{ value: 5, label: 'chatbot' },
{ value: 6, label: 'content marketing' },
{ value: 7, label: 'digital loyalty' },
{ value: 8, label: 'digital transformation' },
{ value: 9, label: 'email marketing' },
{ value: 10, label: 'engagement' },
]
const reactSelectStyleCustom = {
control: (base, state) => ({
...base,
boxShadow: state.isFocused ? 0 : 0,
borderColor: state.isFocused ? '#50A5D2' : base.borderColor,
borderWidth: state.isFocused ? '1px' : '1px',
'&:hover': {
borderColor: state.isFocused ? '#50A5D2' : base.borderColor,
},
}),
placeholder: defaultStyles => {
return {
...defaultStyles,
color: '#A1A1A1',
fontSize: '16px',
}
},
singleValue: provided => {
const overflow = 'visible'
const fontStyle = 'normal'
const transition = 'opacity 300ms'
return { ...provided, overflow, fontStyle, transition }
},
}
return (
<ProductsModal
modalTitle="New Announcement"
handleCloseModal={handleCloseModal}
showModal={showModal}
leftColumn={
<form onSubmit={handleSubmit(onSubmit)}>
<S.FormContainer>
<S.InputTitle>Title</S.InputTitle>
<TextField
fullWidth={true}
variant="outlined"
name="title"
placeholder="Give your announcement a title"
type="text"
value={title}
onChange={e => setTitle(e.target.value)}
/>
<div className="mt-3">
<S.InputTitle>About</S.InputTitle>
<TextField
fullWidth={true}
variant="outlined"
name="about"
multiline
rows="4"
placeholder="Tell them a little more about your announcement"
type="text"
value={about}
onChange={e => setAbout(e.target.value)}
/>
</div>
<div className="mt-3">
<S.InputTitle>Tags</S.InputTitle>
<Select
styles={reactSelectStyleCustom}
isMulti
options={tagsAvailable}
placeholder="Add tags to your announcement"
value={tags}
onChange={handleTagsChange}
/>
</div>
<div className="mt-4 mb-2">
<Border />
</div>
{updatingFile ? (
<div className="mt-2">
<div className="d-flex justify-content-center align-items-center">
<FaRegFileAlt className="mr-2" size={14} />{' '}
<S.InputTitle>Files</S.InputTitle>
</div>
<FilePond
allowMultiple={false}
files={files}
onupdatefiles={setFiles}
/>
</div>
) : (
<div className="d-flex justify-content-center">
<Button
text="Add file"
type="button"
color="#5A6978"
action={handleUpdatingFile}
width="160px"
height="40px"
/>
</div>
)}
{updatingImage ? (
<div className="mt-3">
<div className="d-flex justify-content-center align-items-center">
<FaRegImage className="mr-2" size={14} />{' '}
<S.InputTitle>Images</S.InputTitle>
</div>
<FilePond
allowMultiple={false}
files={images}
onupdatefiles={handleUpdateImages}
/>
</div>
) : (
<div className="d-flex justify-content-center">
<Button
text="Add image"
type="button"
color="#5A6978"
action={handleUpdatingImage}
width="160px"
height="40px"
/>
</div>
)}
<div className="d-flex justify-content-center">
<Button
text="Submit Form"
type="submit"
color="#5A6978"
action={(event) => { event.persist(); handleSubmit(event) }}
width="160px"
height="40px"
/>
</div>
</S.FormContainer>
</form>
}
rightColumn={
<>
<S.Phone>
<S.Screen>
<S.Content>
<div className="image-container">
{filePreview !== '' ? (
<>
<img className="animated fadeIn" src={filePreview} />
<IconsProductImage right="0" top="30%" />
<div className="ml-2 mt-3">
<S.ProductTitle>{title}</S.ProductTitle>
</div>
<div
style={{ marginTop: '-10px' }}
className="d-flex ml-2"
>
<ProductBadge
text="annoucement"
color="#D40707"
textColor="#FFF"
width="135px"
height="30px"
eventText="- engagement"
eventTextColor="#87919A"
/>
</div>
</>
) : (
<>
<img
style={{
postison: 'relative',
backgroundColor: '#CCC',
}}
className="d-flex justify-content-center align-items"
/>
<IoIosImages
style={{
position: 'absolute',
top: '125px',
right: '125px',
}}
color="red"
size={28}
/>
<div className="ml-2 mt-3">
<S.ProductTitle>
{title === '' ? (
'Title'
) : (
<S.ProductTitle>{title}</S.ProductTitle>
)}
</S.ProductTitle>
</div>
<div
style={{ marginTop: '-10px' }}
className="d-flex ml-2"
>
<ProductBadge
text="annoucement"
color="#D40707"
textColor="#FFF"
width="135px"
height="30px"
eventText="- engagement"
eventTextColor="#87919A"
/>
</div>
<S.AboutSection>
<span>{about}</span>
</S.AboutSection>
</>
)}
</div>
</S.Content>
</S.Screen>
<S.Home />
</S.Phone>
</>
}
/>
)
react-hook-form is not built to be used with controlled input elements.
Your input elements have an onChange handler attached to them which is effectively making your form a controlled one. If this is intended, you should pull the setValue method out of useForm and manually update the value to be used with react-hook-form.
See the bottom of this page to read more about using react-hook-form with controlled elements. React Hook Form FAQ

infinite scroll not working properly in React

I am using infinite scroll plugin for react.js and for some reason it is not working the way it is supposed to work.
The problem is that all the requests are made at once when the page loads, and not like for example a request should be made for each time I scroll.
My code looks like below:
import React from 'react';
import {Route, Link} from 'react-router-dom';
import FourthView from '../fourthview/fourthview.component';
import {withRouter} from 'react-router';
import {Bootstrap, Grid, Row, Col, Button, Image, Modal, Popover} from 'react-bootstrap';
import traineeship from './company.api';
import Header from '../header/header.component';
import InfiniteScroll from 'react-infinite-scroller';
require('./company.style.scss');
class Traineeship extends React.Component {
constructor(props) {
super(props);
this.state = {
companies: [],
page: 0,
resetResult: false,
hasMore: true,
totalPages: null,
totalElements: 0,
};
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
fetchCompanies = page => {
let courseIds = '';
this.props.rootState.filterByCourseIds.map(function (course) {
courseIds = courseIds + '' + course.id + ',';
});
traineeship.getAll(page, this.props.rootState.selectedJob, courseIds.substring(0, courseIds.length - 1), this.props.rootState.selectedCity).then(response => {
if (response.data) {
const companies = Array.from(this.state.companies);
if(response.data._embedded !== undefined){
this.setState({
companies: companies.concat(response.data._embedded.companies),
totalPages: response.data.page.totalPages,
totalElements: response.data.page.totalElements,
});
}
if (page >= this.state.totalPages) {
this.setState({hasMore: false});
}
} else {
console.log(response);
}
});
};
render() {
return (
<div className={"wrapperDiv"}>
{/*{JSON.stringify(this.props.rootState)}*/}
<div className={"flexDivCol"}>
<div id="header2">
<div style={{flex: .05}}>
<img src="assets/img/icArrowBack.png" onClick={() => this.props.history.go(-1)}/>
</div>
<div style={{flex: 3}}>
<Header size="small"/>
</div>
</div>
<div id="result">
<div className={"search"}>
<h2 style={{fontSize: 22}}>Harjoittelupaikkoja</h2>
<p className={"secondaryColor LatoBold"} style={{fontSize: 13}}>{this.state.totalElements} paikkaa löydetty</p>
</div>
<div className={"filters"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
<strong>Hakukriteerit</strong></h5>
{
this.props.rootState.filters.map((filter, key) => (
<div key={key} className={"filter"}>{filter.title}</div>
))
}
</div>
<div className={"searchResults"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
<strong>Hakutulokset</strong></h5>
<InfiniteScroll
pageStart={0}
loadMore={this.fetchCompanies}
hasMore={this.state.hasMore}
loader={<div className="loader" key={0}>Loading ...</div>}
useWindow={false}
>
{
this.state.companies.map((traineeship, key) => (
<div id={"item"} key={key}>
<div className={"companyInfo"}>
<div className={"heading"}>
<div id={"companyDiv"}>
<p className={"LatoBlack"} style={{
fontSize: '18px',
lineHeight: '23px'
}}>{traineeship.name}</p>
</div>
{
traineeship.mediaUrl == null
? ''
:
<div id={"videoDiv"}>
<div className={"youtubeBox center"}>
<div id={"youtubeIcon"}>
<a className={"primaryColor"}
href={traineeship.mediaUrl}>
<span style={{marginRight: '3px'}}><Image
src="http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c545.png"
style={{
width: '24px',
height: '17px'
}}/></span>
<span> <p style={{
fontSize: '13px',
lineHeight: '24px',
margin: 0,
display: 'inline-block'
}}>Esittely</p></span>
</a>
</div>
<div id={"txtVideo"}>
</div>
</div>
</div>
}
</div>
<div className={"location"}>
<div id={"locationIcon"}>
<Image src="assets/img/icLocation.png"
style={{marginTop: '-7px'}}/>
</div>
<div id={"address"}>
{
traineeship.addresses.map((address, key) => {
return (
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p key={key} className={"primaryColor"} style={{fontSize: '13px'}}>{address.street}, {address.city}</p>
</a>
)
})
}
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</div>
<div>
{
traineeship.images.map((image, key) => {
return (
<img id={"thumbnail"} width={"100%"}
src={image.url}
style={{
width: '80px',
height: '80px',
marginRight: '10px',
marginBottom: '10px'
}}
alt=""
key={key}
/>
)
})
}
</div>
<div className={"companyContacts"} style={{marginTop: '20px'}}>
<p className={"contactInfo"}>URL: {traineeship.website}</p>
<p className={"contactInfo"}>Email: {traineeship.email}</p>
<p className={"contactInfo"}>Puh: {traineeship.phonenumber}</p>
<p className={"contactInfo"}>Contact: {traineeship.contact}</p>
</div>
</div>
</div>
))
}
</InfiniteScroll>
</div>
</div>
</div>
</div>
);
}
}
export default withRouter(Traineeship);
What can I do so I can eliminate all the request are made when the page is load, I mean this is even worse sending let say 20 request one after another within a second or so.
Any suggestion what is wrong with my code?
by removing useWindow={false} it is working now!
Update: Haven't seen that you are using react-infinite-scroller. If you want to build the loader yourself, see my previous answer. With the plugin you can set a threshold.
The answer lies in here: Question: Infinite Scrolling
What you basically need to do is to set a variable in state, isLoading: false, and change it when data comes in via fetch, when data loading done set it back to false. In your infinite scroll function check (this.state.isLoading).

Uncaught (in promise) TypeError: Cannot read property 'companies' of undefined

I would like to have a list of items with infinite scroll and I am using this package https://github.com/CassetteRocks/react-infinite-scroller but in the documentation there is nothing mentioned how the fetching function looks like.
In my code I have it like this:
this.state = {
companies: [],
page: 0,
resetResult: false,
};
fetchCompanies(page){
traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({ companies: this.state.companies.concat(response.data._embedded.companies) });
} else {
console.log(response);
}
});
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
<InfiniteScroll
pageStart={0}
loadMore={this.fetchCompanies}
hasMore={true || false}
loader={<div className="loader" key={0}>Loading ...</div>}
useWindow={false}
>
{
this.state.companies.map((traineeship, key) => (
<div id={"item"} key={key}>
<div className={"companyInfo"}>
<div className={"heading"}>
<div id={"companyDiv"}>
<p style={{
fontSize: '18px',
lineHeight: '18px'
}}>{traineeship.name}</p>
</div>
{
traineeship.video === null
? ''
:
<div id={"videoDiv"}>
<div className={"youtubeBox center"}>
<div id={"youtubeIcon"}>
<a className={"primaryColor"}
href={traineeship.mediaUrl}>
<span style={{ marginRight: '3px' }}><Image
src="http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c545.png"
style={{
width: '24px',
height: '17px'
}} /></span>
<span> <p style={{
fontSize: '13px',
lineHeight: '18px',
margin: 0,
display: 'inline-block'
}}>Esittely</p></span>
</a>
</div>
<div id={"txtVideo"}>
</div>
</div>
</div>
}
</div>
<div className={"location"}>
<div id={"locationIcon"}>
<Image src="assets/img/icLocation.png" style={{ marginTop: '-7px' }} />
</div>
<div id={"address"}>
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p className={"primaryColor"}
style={{ fontSize: '13px' }}>{traineeship.city}(show in
map)</p>
</a>
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</div>
<div className={"companyContacts"} style={{ marginTop: '20px' }}>
<p className={"contactInfo"}>URL: {traineeship.website}</p>
<p className={"contactInfo"}>Email: {traineeship.email}</p>
<p className={"contactInfo"}>Puh: {traineeship.phonenumber}</p>
<p className={"contactInfo"}>Contact: {traineeship.contact}</p>
</div>
</div>
</div>
))
}
</InfiniteScroll>
Full message error:
Uncaught (in promise) TypeError: Cannot read property 'companies' of
undefined
at eval (traineeships.component.js:71)
Edit: (I no longer have the error but loadmore seems not trigger at all)
import React from 'react';
import {Route, Link} from 'react-router-dom';
import FourthView from '../fourthview/fourthview.component';
import {Bootstrap, Grid, Row, Col, Button, Image, Modal, Popover} from 'react-bootstrap';
import traineeship from './traineeship.api';
import Header from '../header/header.component';
import InfiniteScroll from 'react-infinite-scroller';
require('./traineeship.style.scss');
class Traineeship extends React.Component {
constructor(props) {
super(props);
this.state = {
companies: [],
page: 0,
resetResult: false,
};
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
fetchCompanies(page){
traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({companies: this.state.companies.concat(response.data._embedded.companies)});
} else {
console.log(response);
}
});
}
render() {
return (
<div className={"wrapperDiv"}>
{JSON.stringify(this.props.rootState)}
<div className={"flexDivCol"}>
<div id="header">
<Header/>
</div>
<div id="result">
<div className={"search"}>
<h2>Harjoittelupaikkoja</h2>
<p className={"secondaryColor"}>{this.state.companies.length} paikkaa löydetty</p>
</div>
<div className={"filters"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
Hakukriteerit</h5>
<div className={"filter"}>Ravintola- ja cateringala</div>
<div className={"filter"}>Tarjoilija</div>
<div className={"filter"}>Kaikki</div>
</div>
<div className={"searchResults"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
Hakutulokset</h5>
<InfiniteScroll
pageStart={0}
loadMore={() => this.fetchCompanies.bind(this)}
hasMore={true || false}
loader={<div className="loader" key={0}>Loading ...</div>}
useWindow={false}
>
{
this.state.companies.map((traineeship, key) => (
<div id={"item"} key={key}>
<div className={"companyInfo"}>
<div className={"heading"}>
<div id={"companyDiv"}>
<p style={{
fontSize: '18px',
lineHeight: '18px'
}}>{traineeship.name}</p>
</div>
{
traineeship.video === null
? ''
:
<div id={"videoDiv"}>
<div className={"youtubeBox center"}>
<div id={"youtubeIcon"}>
<a className={"primaryColor"}
href={traineeship.mediaUrl}>
<span style={{marginRight: '3px'}}><Image
src="http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c545.png"
style={{
width: '24px',
height: '17px'
}}/></span>
<span> <p style={{
fontSize: '13px',
lineHeight: '18px',
margin: 0,
display: 'inline-block'
}}>Esittely</p></span>
</a>
</div>
<div id={"txtVideo"}>
</div>
</div>
</div>
}
</div>
<div className={"location"}>
<div id={"locationIcon"}>
<Image src="assets/img/icLocation.png" style={{marginTop: '-7px'}}/>
</div>
<div id={"address"}>
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p className={"primaryColor"}
style={{fontSize: '13px'}}>{traineeship.city}(show in
map)</p>
</a>
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</div>
<div className={"companyContacts"} style={{marginTop: '20px'}}>
<p className={"contactInfo"}>URL: {traineeship.website}</p>
<p className={"contactInfo"}>Email: {traineeship.email}</p>
<p className={"contactInfo"}>Puh: {traineeship.phonenumber}</p>
<p className={"contactInfo"}>Contact: {traineeship.contact}</p>
</div>
</div>
</div>
))
}
</InfiniteScroll>
</div>
</div>
</div>
</div>
);
}
}
export default Traineeship;
So basically it just shows only first five article, page is not increasing!
#Mizlul: Does fetchCompanies invoked every time scroll happens ? Can you please check that ? Also you are mutating the state here, this.state.companies.concat(response.data._embedded.companies)..
Can you update it to ,
const companies = Array.from(this.state.companies);
this.setState({ companies: companies.concat(response.data._embedded.companies) });
I'm not sure about that .bind(this). Try making your method an arrow function (to implicitly bind the this context):
constructor() {
// ...
this.fetchCompanies = this.fetchCompanies.bind(this);
}
fetchCompanies(page) {
return traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({
companies: this.state.companies.concat(
response.data._embedded.companies
)
});
} else {
console.log(response);
}
});
}
// In your render's return:
<InfiniteScroll
pageStart={0}
loadMore={() => this.fetchCompanies(this.state.page)}
hasMore={true || false}
loader={
<div className="loader" key={0}>
Loading ...
</div>
}
useWindow={false}
>;

Categories