React.JS Cannot read property within an Array loop - javascript

I have the following code.
var ImageList = React.createClass({
getComponent: function(index){
console.log(index);
},
render: function() {
var results = this.props.data;
return (
<div className="row">
{results.map(function(result) {
return(
<a className="th medium-3 columns" href="#" onClick= {this.getComponent.bind(this, 1)}>
<img alt="Embedded Image" key={result.id} src={"data:" + result.type + ";" + "base64," + result.image} />
</a>
)
})}
</div>
);
}
});
The second return function basically loops an array of images and shows them. I wanted an OnClick event when clicked should trigger the getComponent method. However if the OnClick event is within the array loop it throws the following error:
Uncaught TypeError: Cannot read property 'getComponent' of undefined.
However if i use the same code and just add the onClick even after the looping function like below:
var ImageList = React.createClass({
getComponent: function(index){
console.log(index);
},
render: function() {
var results = this.props.data;
return (
<div className="row">
{results.map(function(result) {
return(
<img alt="Embedded Image" key={result.id} src={"data:" + result.type + ";" + "base64," + result.image} />
)
})}
<a className="th medium-3 columns" href="#" onClick= {this.getComponent.bind(this, 1)}>
</div>
);
}
});
Ends up working fine. But since i need to keep a unique id for each image only then can i complete the remaining function of getComponent the second method isn't much use for me. Hence is there any way to make it work within the Loop?

Your scope changes within the .map method:
{results.map(function(result) {
// `this` is different inside this anonymous function
})}
What you want to do is either use ES6' fat arrow syntax, which automatically creates an anonymous function with the same scope, or store the current scope of this in a variable:
ES6 Fat Arrow (read more here):
render: function() {
var results = this.props.data;
return (
<div className="row">
{results.map( (result) => {
return(
<a className="th medium-3 columns" href="#" onClick={that.getComponent.bind(that, 1)}>
<img alt="Embedded Image" key={result.id} src={"data:" + result.type + ";" + "base64," + result.image} />
</a>
)
})}
</div>
);
}
});
Note that you'll need a transpiler — such as babel.io — to change this into ES2015 which browsers currently understand to run. This is considered "best practice", as ES6/7 brings better functionality to JS.
Storing a reference to this:
render: function() {
var results = this.props.data,
that = this;
return (
<div className="row">
{results.map(function(result) {
return(
<a className="th medium-3 columns" href="#" onClick={that.getComponent.bind(that, 1)}>
<img alt="Embedded Image" key={result.id} src={"data:" + result.type + ";" + "base64," + result.image} />
</a>
)
})}
</div>
);
}
});

You can use ES6 arrow functions to automatically preserve this context:
results((result) => {
...
})
or just pass this as second param to the map:
results(function(result) {
...
}, this)

Related

Confirm Window in React

I have this following code :
renderPosts() {
return _.map(this.state.catalogue, (catalogue, key) => {
return (
<div className="item col-md-3" key={key} id={key}>
<img src={this.state.catalogue[key].avatarURL} height={150} with={150}/>
<h3>{catalogue.marque}</h3>
<h4>{catalogue.numero}</h4>
<h4>{catalogue.reference}</h4>
<p>{catalogue.cote}</p>
<div className="text-center">
<button className="btn btn-danger" onClick={() => {if(window.confirm('Delete the item?')){this.removeToCollection.bind(this, key)};}}>Supprimer</button>
</div>
</div>
)
})
}
And I have this function too:
removeToCollection(key, e) {
const item = key;
firebase.database().ref(`catalogue/${item}`).remove();
}
When I use the function without a confirm window in my "onclick" button, the code work great. But when I want use a confirm window, the confirm window show when I click on my button, but my item is not delete.
Any idea ?
Thank for your help !
Basically you're binding the function instead of calling it... you should bind beforehand, preferably in the constructor... then call it.
Try this:
renderPosts() {
this.removeToCollection = this.removeToCollection.bind(this);
return _.map(this.state.catalogue, (catalogue, key) => {
return (
<div className="item col-md-3" key={key} id={key}>
<img src={this.state.catalogue[key].avatarURL} height={150} with={150}/>
<h3>{catalogue.marque}</h3>
<h4>{catalogue.numero}</h4>
<h4>{catalogue.reference}</h4>
<p>{catalogue.cote}</p>
<div className="text-center">
<button className="btn btn-danger" onClick={() => {if(window.confirm('Delete the item?')){this.removeToCollection(key, e)};}}>Supprimer</button>
</div>
</div>
)
})
}
You are just binding function and not calling it.
The right synatx to use bind and called binded function.
if (window.confirm("Delete the item?")) {
let removeToCollection = this.removeToCollection.bind(this, 11);//bind will return to reference to binded function and not call it.
removeToCollection();
}
OR you can do like this as well without bind.
if (window.confirm("Delete the item?")) {
this.removeToCollection(11);
}
If this is concern inside removeToCollection then use arrow function to define it.
removeToCollection=(key)=> {
console.log(key);
}
Working codesandbox demo
I did the same as below-
I have a smart(class) component
<Link to={`#`} onClick={() => {if(window.confirm('Are you sure to delete this record?')){ this.deleteHandler(item.id)};}}> <i className="material-icons">Delete</i> </Link>
I defined a function to call the delete endpoint as-
deleteHandler(props){
axios.delete(`http://localhost:3000/api/v1/product?id=${props}`)
.then(res => {
console.log('Deleted Successfully.');
})
}
And that worked for me!

React.js: Set image as div background inside map function

Trying to set image as div background inside map function in React.js project, but I can't access post.featured_image_src outside map function and set as background in the divStyle variable:
class Archive extends Component {
render() {
let allPosts = DataStore.getAllPosts();
let pageData = DataStore.getPageBySlug('archive');
let acf = pageData.acf;
const divStyle = {
backgroundImage: 'url(' + post.featured_image_src + ')'
}
return (
<div>
<h1>{pageData.title.rendered}</h1>
<div className="post-container">
<div className="post-wrapper">
{allPosts.map((post, i) => {
return (
<div className="post" key={i}>
{post.featured_image_src
? <a href={post.link}><div style={divStyle}/></a>
: null}
<h3 className="post-title"><a href={post.link} dangerouslySetInnerHTML={{__html:post.title.rendered}} /></h3>
</div>
)
}
)}
</div>
</div>
</div>
);
}
}
Any tips would be oh so lovely .. <3
The problem is that post is not defined when you try to access it to define styles
const divStyle = {
backgroundImage: 'url(' + post.featured_image_src + ')'
}
You could move have this logic as a function
const divStyle = (src) => ({
backgroundImage: 'url(' + src + ')'
})
return (
<div>
<h1>{pageData.title.rendered}</h1>
<div className="post-container">
<div className="post-wrapper">
{allPosts.map((post, i) => {
return (
<div className="post" key={i}>
{post.featured_image_src
? <a href={post.link}><div style={divStyle(post.featured_image_src)}/></a>
: null}
<h3 className="post-title"><a href={post.link} dangerouslySetInnerHTML={{__html:post.title.rendered}} /></h3>
</div>
)
}
)}
</div>
</div>
</div>
);
For obvious reasons you cannot use the variable before its defined.
You can rather replace <div style={divStyle}/> with:
<div style={ backgroundImage: "url(" + post.featured_image_src + ")" } />
OR, as suggested by #Shubham, use a method that will return the desired style object:
const divStyle = (imgSrc) => ({
backgroundImage: `url(${imgSrc})`
})
In render:
<div style={this.divStyle(post.featured_image_src)}/>
{ post.featured_image_src
? <a href={post.link}>
<div className="post-img" style={{backgroundImage: `url(${post.featured_image_src})`}}/>
</a>
: null
}

Error passing function onClick in react

I have two files. A list Component and a Single Item Component. In my app, the user can select multiples items. Then I create an state element in "list" "items" and my idea is that when the user make click on the item button, the list element notify to List Component and save the item in Items array from "list".
I have the next code
List.jsx:
registrarItems(data,item){
console.log(data,"aqui 1 con",item);
let items = this.state.itemsAgregados.slice();
if(!items.indexOf(data.id_producto)){
console.log("no se encuentra");
items.push(id);
this.setState({
'itemsAgregados':items
});
}else{
console.log("ya existe");
item.removerSeleccion();
}
console.log("registrando items",id);
}
render() {
return (
<div className="content-app">
<Navbar data={this.menu}/>
<div className="container lista-productos">
{
this.state.productos.map((producto, index) => {
return (
<Item data={producto}
registro = {this.registrarItems}
key={producto.id_producto}/>
);
})
}
</div>
</div>
);
}
And Item.jsx:
render() {
let props = this.props;
let img = JSON.parse(props.data.imagen);
let imgPath = Rutas.apiStatic + 'img/productos/' + props.data.id_producto + '/' + img.sm;
props.data.items = this;
return (
<div className="row item-listado">
<div className="col-xs-3">
<img src={imgPath} className="img-circle img-item"/>
</div>
<div className="col-xs-7">
<Link to={Rutas.producto + props.data.identificador}>
<h3 className="titulo">{props.data.titulo}</h3>
<span className="price">$ {props.data.precio}</span>
</Link>
</div>
<div className="col-xs-2 text-right">
<ul className="list-unstyled list-acciones">
<li>
<a href="#" onClick={()=>props.registro(props.data,this)} className={this.state.classAdd}>
<i className="fa fa-plus"></i>
</a>
</li>
</ul>
</div>
</div>
)
}
As you can see, I pass the "registrarItems" method as a param to Item and there, i add this as onClick event in the tag from item. But I need pass the "data" and the own "item" element to the onclick function. The first, for save the element clicked in the Items array, or remove it (if it already exists) because the button may have a toggle function. But in my "console.log" both params passed on the onClick method with the arrow function shows as "undefined".
I saw some examples and i don't get my error. can anybody helpme? thanks.
The final solve for this was simple. I resolved it with something similar as Free-soul said on his comment.
First, I passed the List Component as a param to item. Below my code in List's render method:
{
this.state.productos.map((producto, index) => {
this.items[producto.id_producto] = producto;
return (
<Item data={producto}
parent = {this}
key={producto.id_producto}/>
);
})
}
Then I get the parent param in componentDidMount method and later I call the validarItem function directly from the List method and I pass the params that i need.
Here my Item code:
onClickPlus(id,data) {
//{Rutas.listas + 'productos/' + props.data.id_producto //Url para pasar uno solo
this.setState({
classAdd:'selected'
})
if(!this.state.parent.validarItem(this.state.data)){
this.removerSeleccion()
}
if(this.state.seleccionMultiple){
}
}
removerSeleccion(){
this.setState({classAdd:'normal'})
}
componentDidMount(){
this.setState({
parent: this.props.parent,
data : this.props.data
})
}
render() {
return (
// more code
<a href="#" onClick={() => this.onClickPlus(parent)} className={this.state.classAdd}>
<i className="fa fa-plus"></i>
</a>
//more render code...
)
}
I don't know if this is the best practice, but works for me.

ReactJs: target.key undefined after method is reached from li rendered by map function

I'm currently trying to coding a react app that would do the following:
- Create a list of questions from an array using a map function.
- Making each list element clickable using a onClick prop
- The linked onClick method changes the state in another file with my 'qsChange' prop.
I had a hard time making my list clickable and finally managed following this question: React: trying to add an onClick to a li tag but the click handler function is undefined
However, now I cannot make it so that my variable 'choice' returns a defined value. I would want var choice to be equal to "A ?", "B ?" or "C ?" depending on which I click.
Here's my code:
var questions = ["A ?", "B ?", "C ?"];
var Questions = React.createClass({
handleClick: function() {
var visibility;
if(this.props.visibility) {
document.getElementById('second').style.display = 'none';
visibility = false;
this.props.onChange(visibility);
} else {
document.getElementById('second').style.display = 'block';
visibility = true;
this.props.onChange(visibility);
}
},
/* Here is where my problem lies */
onItemClick: function(e){
var choice = e.target.key;
this.props.qsChange(choice);
alert(choice);
},
render: function() {
return (
<div className="bigqs">
<div id="first" className="small" style={firstStyle}>
<h1>Question :</h1>
<button style={btnStyle} onClick={this.handleClick}>
<img id="arrow" src="../../img/arrow.png" />
</button>
<h3 id="selectedQuestion">{this.props.selected}</h3>
</div>
<div id="second" className="small" style={{display: 'none'}}>
<h4>
<ul>
{questions.map(function(qs, i) {return <li key={qs[i]} onClick={this.onItemClick}>{qs}</li>;}, this)}
</ul>
</h4>
</div>
</div>
);
}
});
I am still a newbie, so please be indulgent ;-)
I hope I was clear enough.
Ps: I have also tried this guide but it didn't work for me: http://derpturkey.com/react-pass-value-with-onclick/
Instead of grabbing the question from target, you can pass question through to your handler. Also, since inside map qs is a string, qs[i] will be getting the character in the string from that index. You just need to make sure your key is unique.
onItemClick: function(choice) {
this.props.qsChange(choice)
alert(choice)
},
render() {
return (
<div>
...
{questions.map(qs =>
<li key={qs} onClick={() => this.onItemClick(qs)}>{qs}</li>
)}
...
</div>
)
}
In fact, your intermediate function isn't doing much, you can just call your props function inside render:
render() {
return (
<div>
...
{questions.map(qs =>
<li key={qs} onClick={() => this.props.qsChange(qs)}>{qs}</li>
)}
...
</div>
)
}

I think this is another React/JS context issue, how do I extract this variable?

I have an array[] of tracks that I receive from an API.
I pass it to a map function which will return a track for every track in tracks. I want to export a variable (Song) specific to that track to be be processed in my event handler as such. The only thing thats not working is the scope of song. I cant set the state of song in my map function or the component goes into an infinite rerender loop.
handleEnter(){
//I want to get the song into this context and play it here
this.props.mouseEnter();
}
handleLeave(){
//same for pausing
this.props.mouseLeave();
}
createTrack(track){
var song = new Audio([track.preview_url]);
return (
<div className="image" key={track.id}>
<img
className="img-circle"
src={track.album.images[0].url}
onMouseEnter={this.handleEnter.bind(this)}
onMouseLeave={this.handleLeave.bind(this)}
/>
<p className="showMe"><span>{track.name}</span></p>
</div>
);
}
getTracks(){
if(this.props.tracks) {
console.log(this.props.tracks);
return (
<div>{this.props.tracks.map(track => this.createTrack(track))}</div>
);
}
}
componentWillMount(){
this.props.fetchMessage();
}
render(){
return(
<div>{this.getTracks()}</div>
)
}
if you want to use .bind, you can send it to handleEnter and handleLeave.
handleEnter( trackID ) {
// trackID available here
}
createTrack(track){
var song = new Audio([track.preview_url]);
return (
<div className="image" key={track.id}>
<img
className="img-circle"
src={track.album.images[0].url}
onMouseEnter={this.handleEnter.bind( this, track.id )}
onMouseLeave={this.handleLeave.bind( this, track.id )}
/>
<p className="showMe"><span>{track.name}</span></p>
</div>
);
}
It's typically best practice to not use .bind in react since it creates a new function on every render. Rather, you should create a <Track /> component, pass it the track, then pass handleEnter and handleLeave as props.
const track = ( props ) => {
let { track, handleEnter, handleLeave } = props;
const onMouseEnter = () {
handleEnter( track.id );
}
const onMouseLeave = () {
handleLeave( track.id );
}
return (
<div className="image" key={track.id}>
<img
className="img-circle"
src={track.album.images[0].url}
onMouseEnter={ onMouseEnter }
onMouseLeave={ onMouseLeave }
/>
<p className="showMe">
<span>{track.name}</span>
</p>
</div>
);
};
then in your render, you'd map like you're doing and output <Track /> pure components instead of full-on components
Have a look at this. Hopefully it will solve your problem.
handleEnter(track, e){
// you will get the full track object and use the data
this.props.mouseEnter();
}
handleLeave(track, e){
// you will get the full track object and use the data
this.props.mouseLeave();
}
componentWillMount(){
this.props.fetchMessage();
}
render(){
const createTrack = (track, index) => {
var song = new Audio([track.preview_url]);
return (
<div className="image" key={'track-'+ index}>
<img
className="img-circle"
src={track.album.images[0].url}
onMouseEnter={this.handleEnter.bind(this, track)}
onMouseLeave={this.handleLeave.bind(this,track)}
/>
<p className="showMe"><span>{track.name}</span></p>
</div>
);
}
return(
<div>{this.props.tracks ? this.props.tracks.map(createTrack) : null }</div>
)
}

Categories