I'm new to React.js and maybe this question is kinda vague, please be kind. I am using react-image-gallery to create a gallery in my component. This gallery component has a prop of callback function onImageLoad which is called when an image is loaded (i am using lazy-loading). The problem is that this onImageLoad prop is able to do direct console.log('called') but it doesn't fire any event. So this works:
class Post extends React.Component {
render() {
return (
<ImageGallery onImageLoad={console.log('called')} />
)
}
}
But these don't work:
class Post extends React.Component {
EVENTNAME = e => {
console.log('called', e);
}
render() {
return (
<ImageGallery onImageLoad={this.EVENTNAME.bind(this)} />
)
}
}
This doesn't work either:
class Post extends React.Component {
EVENTNAME = e => {
console.log('called', e);
}
render() {
return (
<ImageGallery onImageLoad={e => this.EVENTNAME} />
)
}
}
Nor this one:
class Post extends React.Component {
EVENTNAME = e => {
console.log('called', e);
}
render() {
return (
<ImageGallery onImageLoad={e => console.log('called', e)} />
)
}
}
have tried this too:
class Post extends React.Component {
EVENTNAME = e => {
console.log('called', e);
}
render() {
return (
<ImageGallery onImageLoad={this.EVENTNAME} />
)
}
}
I'm guessing this is a problem of function scoping and something like that. Some hints and guidance will be appreciated. Thanks!
View Full File Code Here
are you getting error like ,'EVENTNAME' is not defined no-undef
if that's the case,
add declaration in front of function definition.
let EVENTNAME = e => {
console.log('called', e);
}
Problem solved define your images as
import React from "react";
import ImageGallery from "react-image-gallery";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
slidesLoaded: 0
};
}
images = [
{
original: "https://picsum.photos/id/1018/1000/600/",
thumbnail: "https://picsum.photos/id/1018/250/150/"
},
{
original: "https://picsum.photos/id/1015/1000/600/",
thumbnail: "https://picsum.photos/id/1015/250/150/"
},
{
original: "https://picsum.photos/id/1019/1000/600/",
thumbnail: "https://picsum.photos/id/1019/250/150/"
}
];
checkAndShowSlider = e => {
console.log("called", e);
let count = this.images.length;
let nowLoaded = this.state.slidesLoaded + 1;
if (nowLoaded === count) {
document.querySelector(".images.section").css("display", "block");
}
this.setState(() => {
return {
slidesLoaded: nowLoaded
};
});
};
render() {
return (
<div className="App">
<ImageGallery
onImageLoad={e => this.checkAndShowSlider(e)}
items={this.images}
showPlayButton={false}
thumbnailPosition="left"
useBrowserFullscreen={false}
/>
</div>
);
}
}
export default App;
Related
Edit: I have included the full code for better clarity
I am not sure if this is possible. I am trying to pass an onClick event via props but the click event does not work.
The parent component looks like this:
import React from 'react'
import { getProductsById } from '../api/get'
import Product from './Product'
import { instanceOf } from 'prop-types'
import { withCookies, Cookies } from 'react-cookie'
class Cart extends React.Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
}
constructor(props) {
super(props)
const { cookies } = props;
this.state = {
prods: cookies.get('uircartprods') || '',
collapsed: true,
total: 0,
}
this.expand = this.expand.bind(this)
this.p = [];
}
componentDidMount() {
this.getCartProducts()
}
handleClick = (o) => {
this.p.push(o.id)
const { cookies } = this.props
cookies.set('uircartprods', this.p.toString(), { path: '/' , sameSite: true})
this.setState({prods: this.p })
console.log('click')
}
getCartProducts = async () => {
let products = []
if (this.state.prods !== '') {
const ts = this.state.prods.split(',')
for (var x = 0; x < ts.length; x++) {
var p = await getProductsById(ts[x])
var importedProducts = JSON.parse(p)
importedProducts.map(product => {
const prod = <Product key={product.id} product={product} handler={() => this.handleClick(product)} />
products.push(prod)
})
}
this.setState({products: products})
}
}
expand(event) {
this.setState({collapsed: !this.state.collapsed})
}
handleCheckout() {
console.log('checkout clicked')
}
render() {
return (
<div className={this.state.collapsed ? 'collapsed' : ''}>
<h6>Your cart</h6>
<p className={this.state.prods.length ? 'hidden' : ''}>Your cart is empty</p>
{this.state.products}
<h6>Total: {this.props.total}</h6>
<button onClick={this.handleCheckout} className={this.state.prods.length ? '' : 'hidden' }>Checkout</button>
<img src="./images/paypal.png" className="paypal" alt="Paypal" />
<a className="minify" onClick={this.expand} alt="My cart"></a>
<span className={this.state.prods.length ? 'pulse' : 'hidden'}>{this.state.prods.length}</span>
</div>
)
}
}
export default withCookies(Cart)
The Product component:
import React from 'react';
class Product extends React.Component {
constructor(props) {
super(props);
this.state = {
showDetails: false,
showModal: false,
cart: []
}
this.imgPath = './images/catalog/'
}
render() {
return (
<div className="Product">
<section>
<img src={this.imgPath + this.props.product.image} />
</section>
<section>
<div>
<h2>{this.props.product.title}</h2>
<h3>{this.props.product.artist}</h3>
<p>Product: {this.props.product.product_type}</p>
<h4>${this.props.product.price}</h4>
<button className="button"
id={this.props.product.id} onClick={this.props.handler}>Add to cart</button>
</div>
</section>
</div>
)
}
}
export default Product
If I log this.props.handler I get undefined. Everything works apart from the click handler, I was wondering if it might have something to with the async function. I am very new to React, there are still some concepts I'm not sure about, so any help is appreciated.
Okay, I see a few issues here.
First, there is no need to call this.handleClick = this.handleClick.bind(this) in the constructor, because you are using an arrow function. Arrow functions do not have a this context, and instead, accessing this inside your function will use the parent this found in the Class.
Secondly, it is wrong to store components in state. Instead, map your importedProducts inside the render function.
Thirdly, the issue with your handler is that this.props.handler doesn't actually call handleClick. You will notice in the definition handler={(product) => this.handleClick} it is returning the function to the caller, but not actually calling the function.
Try this instead.
class Product extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<button className="button" id={this.props.product.id} onClick={this.props.handler}>
Add to cart
</button>
</div>
);
}
}
export default Product;
import Product from './Product'
class Cart extends React.Component {
constructor(props) {
super(props);
}
handleClick = (o) => {
console.log('click');
};
render() {
return (
<div>
{importedProducts.map((product) => {
return <Product key={product.id} product={product} handler={() => this.handleClick(product)} />;
})}
</div>
);
}
}
export default Cart;
I have the below where it should display images of beers retrieved from an API. Each image has a handleClick event which will direct them to a details page about this beer. My code below doesn't render the beers at all and goes straight to the details page of a random beer. Can anyone help me figure out why?
Thanks
export default class GetBeers extends React.Component {
constructor() {
super();
this.state = {
beers: [],
showMethod: false,
beerDetails: []
};
this.getBeerInfo = this.getBeerInfo.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleClick(details) {
this.setState({
showMethod: !this.state.showMethod,
beerDetails: details
});
}
render() {
if(this.state.showMethod) {
return (
<Beer details = {this.state.beerDetails}/>
);
}
else {
return (
<div>{this.state.beers.map(each=> {
return <img className = "img-beer" onClick = {this.handleClick(each)} src={each.image_url}/>
})}</div>
);
}
}
componentDidMount() {
this.getBeerInfo()
}
getBeerInfo() {
...gets info
}
}
When you use onClick like that you run the function at the render.
So you have to use arrow function:
Not Working:
<img className = "img-beer" onClick = {this.handleClick(each)} src={each.image_url}/>
Working:
<img className = "img-beer" onClick = {() => this.handleClick(each)} src={each.image_url}/>
The main issue is not calling the handle properly.
Also, I noticed that you are binding the functions in the constructor. It might be simpler to use ES6 function creation, so the scope of the class is bound to your handle method.
export default class GetBeers extends React.Component {
constructor() {
super();
this.state = {
beers: [],
showMethod: false,
beerDetails: []
};
}
handleClick = (details) => {
this.setState({
showMethod: !this.state.showMethod,
beerDetails: details
});
}
render() {
if(this.state.showMethod) {
return (
<Beer details = {this.state.beerDetails}/>
);
}
else {
return (
<div>{this.state.beers.map(each=> {
return <img className = "img-beer" onClick = {() => this.handleClick(each)} src={each.image_url}/>
})}</div>
);
}
}
componentDidMount() {
this.getBeerInfo()
}
getBeerInfo = () => {
...gets info
}
}
I'm new to React and I'm trying to build a search filter fetching an API, the console doesn't give me any error, but the filter search bar doesn't work, could someone help me out? Thank you!
So, I think everything should be fine, because in the chrome console, I don't receive any errors, but the SearchBox.js, doesn't seem to work
This is the code:
SearchBox.js:
import React from 'react';
class SearchBox extends React.Component {
constructor(props) {
super(props)
this.state = {
suggestions: [],
text: '',
}
}
componentDidMount() {
fetch('https://api.scryfall.com/catalog/card-names')
.then(response => response.json())
.then(cards => this.setState({ suggestions: cards.data}))
}
onTextChanged = (event) => {
const { items } = this.props;
const value = event.target.value;
let suggestions = [];
if (value.length > 0) {
const regex = new RegExp(`^${value}`, '');
suggestions = Object.keys(items).sort().filter(word => regex.test(word))
}
this.setState(() => ({ suggestions, text: value }))
}
suggestionSelected (value) {
this.setState({
text: value,
suggestions: []
});
}
renderSuggestions () {
const { suggestions } = this.state;
if (suggestions.length === 0) {
return null;
}
return (
<ul>
{suggestions.map((item, index) => <li key={index} onClick={() => this.suggestionSelected(item)}>{item}</li>)}
</ul>
)
}
render () {
const { text } = this.state;
return (
<div>
<input value={text}
onChange={this.onTextChanged} type="text" />
{this.renderSuggestions()}
</div>
);
}
}
export default SearchBox;
App.js:
import React from 'react';
import SearchBox from './components/SearchBox';
class App extends React.Component{
render() {
return(
<div>
<SearchBox items/>
</div>
)
}
};
export default App;
You are missing the functions bindings:
class SearchBox extends React.Component {
constructor(props) {
super(props)
this.state = {
suggestions: [],
text: '',
}
// == Binding ==
this.suggestionSelected = this.suggestionSelected.bind(this);
this.renderSuggestions = this.renderSuggestions.bind(this);
this.onTextChanged = this.onTextChanged.bind(this);
// == ======= ==
}
// [...]
}
I have a gallery that show images, and i have a search textbox
Im Trying to use Timeout on Input event to prevent the api call on every letter im typing :
I try to handle the event with doSearch function onChange: but now I cant write anything on the textbox and it cause many errors
Attached to this session the app and gallery components
Thanks in advance
class App extends React.Component {
static propTypes = {
};
constructor() {
super();
this.timeout = 0;
this.state = {
tag: 'art'
};
}
doSearch(event){
var searchText = event.target.value; // this is the search text
if(this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(function(){this.setState({tag: event.target.value})} , 500);
}
render() {
return (
<div className="app-root">
<div className="app-header">
<h2>Gallery</h2>
<input className="input" onChange={event => this.doSearch(event)} value={this.state.tag}/>
</div>
<Gallery tag={this.state.tag}/>
</div>
);
}
}
export default App;
This is the Gallery class:
import React from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import Image from '../Image';
import './Gallery.scss';
class Gallery extends React.Component {
static propTypes = {
tag: PropTypes.string
};
constructor(props) {
super(props);
this.state = {
images: [],
galleryWidth: this.getGalleryWidth()
};
}
getGalleryWidth(){
try {
return document.body.clientWidth;
} catch (e) {
return 1000;
}
}
getImages(tag) {
const getImagesUrl = `services/rest/?method=flickr.photos.search&api_key=522c1f9009ca3609bcbaf08545f067ad&tags=${tag}&tag_mode=any&per_page=100&format=json&safe_search=1&nojsoncallback=1`;
const baseUrl = 'https://api.flickr.com/';
axios({
url: getImagesUrl,
baseURL: baseUrl,
method: 'GET'
})
.then(res => res.data)
.then(res => {
if (
res &&
res.photos &&
res.photos.photo &&
res.photos.photo.length > 0
) {
this.setState({images: res.photos.photo});
}
});
}
componentDidMount() {
this.getImages(this.props.tag);
this.setState({
galleryWidth: document.body.clientWidth
});
}
componentWillReceiveProps(props) {
this.getImages(props.tag);
}
render() {
return (
<div className="gallery-root">
{this.state.images.map((dto , i) => {
return <Image key={'image-' + dto.id+ i.toString()} dto={dto} galleryWidth={this.state.galleryWidth}/>;
})}
</div>
);
}
}
First of all why do you need to use setTimeout to set value that is entered by user. I don't see any use using setTimeout in doSearch function.
The reason your doSearch function won't work because you are not binding it.
You can directly set value to tag using setState in doSearch function in following ways.
ES5 way
constructor(props){
super(props);
this.doSearch = this.doSearch.bind(this);
}
doSearch(event){
this.setState({
tag: event.target.value
});
}
ES6 way
doSearch = (event) => {
this.setState({
tag: event.target.value
});
}
Doing setState inside setTimeout in doSearch function won't work because
input tag has value assigned.
ES5 way
constructor(props){
super(props);
this.doSearch = this.doSearch.bind(this);
}
doSearch(event){
if(this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(function(){
this.setState({
tag: event.target.value
})
}.bind(this),500);
}
setTimeout in ES6 way
doSearch = (event) => {
if(this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.setState({
tag: event.target.value
})
},500);
}
Gallery component:
Check current props changes with previous change in componentWillRecieveProps to avoid extra renderings.
Try with below updated code
import React from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import Image from '../Image';
import './Gallery.scss';
class Gallery extends React.Component {
static propTypes = {
tag: PropTypes.string
};
constructor(props) {
super(props);
this.state = {
images: [],
galleryWidth: this.getGalleryWidth()
};
}
getGalleryWidth(){
try {
return document.body.clientWidth;
} catch (e) {
return 1000;
}
}
getImages(tag) {
const getImagesUrl = `services/rest/?method=flickr.photos.search&api_key=522c1f9009ca3609bcbaf08545f067ad&tags=${tag}&tag_mode=any&per_page=100&format=json&safe_search=1&nojsoncallback=1`;
const baseUrl = 'https://api.flickr.com/';
axios({
url: getImagesUrl,
baseURL: baseUrl,
method: 'GET'
})
.then(res => res.data)
.then(res => {
if (
res &&
res.photos &&
res.photos.photo &&
res.photos.photo.length > 0
) {
this.setState({images: res.photos.photo});
}
});
}
componentDidMount() {
this.getImages(this.props.tag);
this.setState({
galleryWidth: document.body.clientWidth
});
}
componentWillReceiveProps(nextProps) {
if(nextProps.tag != this.props.tag){
this.getImages(props.tag);
}
}
shouldComponentUpdate(nextProps, nextState) {
if(this.props.tag == nextProps.tag){
return false;
}else{
return true;
}
}
render() {
return (
<div className="gallery-root">
{this.state.images.map((dto , i) => {
return <Image key={'image-' + dto.id+ i.toString()} dto={dto} galleryWidth={this.state.galleryWidth}/>;
})}
</div>
);
}
}
I am keeping tag initial value to empty as you are not doing anything with value art.
Please try with below code
class App extends React.Component {
static propTypes = {
};
constructor() {
super();
this.timeout = 0;
this.state = {
tag: '',
callGallery: false
};
}
doSearch = (event) => {
this.setState({tag: event.target.value, callGallery: false});
}
handleSearch = () => {
this.setState({
callGallery: true
});
}
render() {
return (
<div className="app-root">
<div className="app-header">
<h2>Gallery</h2>
<input className="input" onChange={event => this.doSearch(event)} value={this.state.tag}/>
<input type="button" value="Search" onClick={this.handleSearch} />
</div>
{this.state.callGallery && <Gallery tag={this.state.tag}/>}
</div>
);
}
}
export default App;
This is because you haven't bound this to your method.
Add the following to your constructor:
this.doSearch = this.doSearch.bind(this);
Also, you don't need the fat arrow notation for onChange. Just do:
onChange={this.doSearch}
onChange handler is just fine but you need to bind the setTimeout to render context.Currently,it is referring to window context.And the code as follows
doSearch(event){
var searchText = event.target.value; // this is the search text
if(this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(function(){
this.setState({
tag: event.target.value
})
}.bind(this),500);
}
I'm beginner on react and i've written the code below:
class Note extends React.Component {
constructor(props) {
super(props);
this.state = {editing: false};
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
edit() {
// alert('edit');
this.setState({editing: !this.state.editing});
}
save() {
this.props.onChange(this.refs.newVal.value, this.props.id);
this.setState({editing: !this.state.editing});
// console.log('save is over');
}
renderForm() {
return (
<div className="note">
<textarea ref="newVal"></textarea>
<button onClick={this.save}>SAVE</button>
</div>
);
}
renderDisplay() {
return (
<div className="note">
<p>{this.props.children}</p>
<span>
<button onClick={this.edit}>EDIT</button>
<button onClick={this.remove}>X</button>
</span>
</div>
);
}
render() {
console.log(this.state.editing);
return (this.state.editing) ? this.renderForm()
: this.renderDisplay()
}
}
class Board extends React.Component {
constructor(props){
super(props);
this.state = {
notes: []
};
this.update = this.update.bind(this);
this.eachNote = this.eachNote.bind(this);
this.add = this.add.bind(this);
}
nextId() {
this.uniqeId = this.uniqeId || 0;
return this.uniqeId++;
}
add(text) {
let notes = [
...this.state.notes,
{
id: this.nextId(),
note: text
}
];
this.setState({notes});
}
update(newText, id) {
let notes = this.state.notes.map(
note => (note.id !== id) ?
note :
{
id: id,
note: newText
}
);
this.setState({notes})
}
eachNote(note) {
return (<Note key={note.id}
id={note.id}
onChange={this.update}>
{note.note}
</Note>)
}
render() {
return (<div className='board'>
{this.state.notes.map(this.eachNote)}
<button onClick={() => this.add()}>+</button>
</div>)
}
}
ReactDOM.render(<Board />,
document.getElementById('root'));
In render(), onClick event has a function, that is, if used in this way: {this.add} the following error is created:
Uncaught Error: Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, nativeEvent, type, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, ...})
Why? while in the eachNote() method this command is used:
onChange={this.update}
And there was no error.
Someone can tell me the reason? thanks.
The problem is that in the add function you are taking an argument text and setting it in the state so when you call onClick={() => this.add()}, you are not passing any argument to add function and hence in its definition text is undefned and hence state note is set as undefined.
However if you directly call it like onClick={this.add} , the add function receives the event object as a parameter and hence it sets state note to be an event object which you are using to render
onClick={this.add} will pass the click event to this.add.
So what you need to do is either:
onClick={e => this.add('some text')} or similar.
If you want to onClick={this.add} you have to ensure that your add method is: add(event) { ... } instead.
The <Note /> component does not contain a render() method to return anything. Add a render() method and return something.
class Note extends React.Component {
constructor(props) {
super(props);
this.state = {editing: false};
this.edit = this.edit.bind(this);
}
edit() {
// alert('edit');
this.setState({editing: !this.state.editing});
}
render() {
return (
<div>Render something</div>
)
}
}
class Board extends React.Component {
constructor(props){
super(props);
this.state = {
notes: []
};
this.update = this.update.bind(this);
this.eachNote = this.eachNote.bind(this);
this.add = this.add.bind(this);
}
nextId() {
this.uniqeId = this.uniqeId || 0;
return this.uniqeId++;
}
add(text) {
let notes = [
...this.state.notes,
{
id: this.nextId(),
note: text
}
];
this.setState({notes});
}
update(newText, id) {
let notes = this.state.notes.map(
note => (note.id !== id) ?
note :
{
id: id,
note: newText
}
);
this.setState({notes})
}
eachNote(note) {
return (<Note key={note.id}
id={note.id}
onChange={this.update}>
{note.note}
</Note>)
}
render() {
return (<div className='board'>
{this.state.notes.map(this.eachNote)}
<button onClick={() => this.add()}>+</button>
</div>)
}
}
ReactDOM.render(<Board />,
document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="root"></div>