Unexpected token with es6 map in reactjs - javascript

I have this in jsx where is an array like breadcrumb = ['food','hotdogt'] but I got an error of unexpected token .?
{breadcrumb.map(obj => {
{obj}
})}

Write it like this:
{
breadcrumb.map(obj => {
return <div> {obj} </div>
})
}
or
{
breadcrumb.map(obj => <div> {obj} </div>)
}
or
{
breadcrumb.map(obj => obj)
}
{} braces are required when you are using js code inside html element, you are using {obj} but didn't use any html element. And you forgot to use return also.
Check this example:
var breadcrumb = ['food','hotdogt'];
var App = () => {
return(
<div>
{
breadcrumb.map(obj => <p key={obj}> {obj} </p>)
}
{
breadcrumb.map((obj, i) => {
return <span key={obj}>
<span className="bold"> {obj} </span>
{i != breadcrumb.length -1 ? <span className="seperator"> -> </span> : null}
</span>
})
}
</div>
)
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>

Related

If-else statement in .map loop in JSX

Instagram clone:
I want to check if I follow my follower then display <button>unfollow</button> or if not display <button>follow</button>
var IfollowAndHeFollowMe;
myfollowers.map(follower => {
return(
<div>
<div>{follower.userName}</div>
{ IfollowAndHeFollowMe =
myfollowings.filter((following) => following.userName == follower.userName)
}
// this doesn't work
{ IfollowAndHeFollowMe.length > 0 ? return( <button>unfollow</button>): return(<button>follow</button>) }
// and this also doesn't work
{ return IfollowAndHeFollowMe.length > 0 ? <button>unfollow</button> : <button>follow</button>}
</div>
)
})
//https://instagram-app-clone.netlify.app/ --- just for phone ---
JSX Code inside {} should be written as statements.
https://reactjs.org/docs/conditional-rendering.html
const followers = ['John', 'Hanna'];
function RenderMap() {
return (
<React.Fragment>
{followers.map(follower => (
<div>
<span>{follower}</span>
{followers.length > 0 ? (
<button>unfollow</button>
) : (
<button>follow</button>
)}
</div>
))}
</React.Fragment>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
// now dont have errors but its allways display button with follow text
{Data[2][0].followers.map(follower => {
idFollowers++;
return (
<div className="follower" id={idFollowers} >
<img src={follower.profilna} className="profilnaFollower" alt="" />
<div className="userInfoFollower">
<h3>{follower.userName}</h3>
<p>{follower.name}</p>
</div>
{dbFollow = Object.entries(Data[2][0].following).filter(following => following.userName == follower.userName)}
{dbFollow.length > 0 ? (<button>unfoldasdaslow</button>) : (<button>fodsadsllow</button>)}
</div>
)
})}
</div>

ReactJS: Map array of objects

I am trying to map array of objects [{thing: '', quantity: ''}] with ReactJS and this is the code i use for it (and it does not work).
EDIT this is the original code
<ul>
{this.state.ingredients.map(({i,q},k)=>{
return (
<div key={k}>
<li>{i} - {q}</li><br/>
</div>
)
})}
</ul>
what is the reason?
Pass the properties to your map. When destructuring objects, you need to provide the exact keys.
for example, doing the following returns undefined, since obj doesn't have the given props. Object_destructuring
const obj = {a: 'a', b: 'b'}
const { c, d} = obj;
console.log(c, d);
{this.state.things.map(({ thing, quantity }, k) => {
return (
<div key={k}>
<li key={k}>{thing} - {quantity}</li><br />
</div>
)
})}
DEMO
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component {
constructor() {
super();
this.state = {
name: 'React',
things: [{ thing: 'Thing ', quantity: 23 }],
};
}
render() {
return (
<div>
{this.state.things.map(({ thing, quantity }, k) => {
return (
<div key={k}>
<li key={k}>{thing} - {quantity}</li><br />
</div>
)
})}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
</script>
Probably you are looking for something like this, you are not destructuring correctly.
const obj = {thing:'something',quantity:1};
const arr = [obj];
{
arr.map(({ thing, quantity }, index) => {
return (
<div key={index}>
<li>{thing} - {quantity}</li><br/>
</div>
)
})}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

How to remove a button if there is no more info in the api

The following code is running smoothly, but I want to implement it in a way that when I do a getNextPers() and there is no info, it hides/removes the Ver Mais button. I've been looking for solutions but have found none, so any help is good. Thank you.
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class List extends React.Component {
constructor(props){
super(props);
this.state = {
personagens: [],
page: 1,
showBtn: true,
};
this.getNextPers = this.getNextPers.bind(this);
}
getNextPers(){
const peopleApiEndpoint = `https://swapi.co/api/people/${this.state.page}`;
axios.get(peopleApiEndpoint).then((p) =>
if(p=={}){
this.setState({ showBtn: false });
}
else {
this.setState({ personagens: this.state.personagens.concat(p), page: this.state.page+1 })
}
);
}
render(){
return (
<div>
<p><b>Personagens:</b></p>
{this.state.personagens.map((pers, i) => (
<div key={i}>
<br />
<p><i>Name:</i> {pers.data.name}</p>
<p><i>Height:</i> {pers.data.height} cm</p>
<p><i>Mass:</i> {pers.data.mass} kg</p>
</div>
))}
<button onClick={this.getNextPers}>Ver Mais</button>
</div>
);
}
}
ReactDOM.render(<List />, document.getElementById('root'));
The real problem is here:
axios.get(peopleApiEndpoint).then((p) => {
if (p == {}) { // THIS WILL NEWER WORK AS EXPECTED
this.setState({showBtn: false});
} else {
this.setState({
personagens: this.state.personagens.concat(p),
page: this.state.page + 1
});
}
});
Also swapi return 404 when there is no more results instead of empty object so you need to add catch block to your axios.get as described in docs: https://github.com/axios/axios#handling-errors
axios.get(peopleApiEndpoint).then((p) => {
this.setState({
personagens: this.state.personagens.concat(p),
page: this.state.page + 1
});
}).catch((err) => {
this.setState({showBtn: false});
});
Now you can use conditional rendering like:
{(this.state.showBtn && <button onClick={this.getNextPers}>Ver Mais</button>)}
First thing getNextPers does not return anything and you can achieve the show/hide by using condintion in your code
{ this.your_condition ?
<button onClick={this.getNextPers}>Ver Mais</button> : ''
}
As addition to Ramya answer you can also use
render(){
return (
<div>
<p><b>Personagens:</b></p>
{this.state.personagens.map((pers, i) => (
<div key={i}>
<br />
<p><i>Name:</i> {pers.data.name}</p>
<p><i>Height:</i> {pers.data.height} cm</p>
<p><i>Mass:</i> {pers.data.mass} kg</p>
</div>
))}
{ this.state.showBtn && <button onClick={this.getNextPers}>Ver Mais</button> }
</div>
);
}
Since you're storing the showBtn state in your component, you can use it to conditionally render the button as follows:
render(){
return (
<div>
<p><b>Personagens:</b></p>
{this.state.personagens.map((pers, i) => (
<div key={i}>
<br />
<p><i>Name:</i> {pers.data.name}</p>
<p><i>Height:</i> {pers.data.height} cm</p>
<p><i>Mass:</i> {pers.data.mass} kg</p>
</div>
))}
{ (this.state.showBtn) ?
<button onClick={this.getNextPers}>Ver Mais</button>
:
null
}
</div>
);
}

React: How to show message when result is zero in react

How to show No Result message when the search result is empty with in map() ?
export class Properties extends React.Component {
render () {
const { data, searchText } = this.props;
const offersList = data
.filter(offerDetail => {
return offerDetail.city.toLowerCase().indexOf(searchText.toLowerCase()) >= 0;
})
.map(offerDetail => {
return (
<div className="offer" key={offerDetail.id}>
<h2 className="offer-title">{offerDetail.title}</h2>
<p className="offer-location"><i className="location-icon"></i> {offerDetail.city}</p>
</div>
);
});
return (
<main>
<div className="container">
<h1>Main {offersList.length}</h1>
{ offersList }
</div>
</main>
);
}
}
With a ternary operator:
<main>
<div className="container">
<h1>Main {offersList.length}</h1>
{ offersList.length ? offersList : <p>No result</p> }
</div>
</main>
If offersList array is empty, it's length will equal to 0. You can make easy condition:
<div className="container">
<h1>Main {offersList.length}</h1>
{ offersList.length ? offersList : <p>No Result</p> }
</div>
{offersList.length ? (
// html markup with results
) : (
// html markup if no results
)}

How to return data in a react .map statement?

I want to use warningItem within my return statement in order to map some data into a react component.
I want to loop over area but have problems with syntax.
createWarnings = warningsRawData => {
return warningsRawData.map(warningItem => {
return (
<div>
<p className={styles.warningMainText} />
<p>warningItem.area[0]</p>
</div>
);
});
};
It looks like you are missing the brackets around it. Try:
createWarnings = warningsRawData => {
return warningsRawData.map( (warningItem, i) => {
return (
<div key={i}>
<p className={styles.warningMainText} />
<p>{warningItem.area[0]}</p>
</div>
);
});
};
Whenever you loop to return elememnt in react, add key attribute is must. Else you will get warning.And add {warningItem.area[0]}
createWarnings = warningsRawData => {
let values = warningsRawData.map((warningItem,index) => {
return (
<div key={index}>
<p className={styles.warningMainText} />
<p>{warningItem.area[0]}</p>
</div>
);
});
return values
}
;

Categories

Resources