jsx Failed to compile Unexpected Token - javascript

Its difficult for me to understand the errors in this JSX code. It feels like I am applying the correct conventional rules for JSX but below I've posted the feedback that I've received from the console and it seems to stem from the first forEach method inside of the promise.
class EventQueries extends Component{
constructor(props){
super(props);
this.state = {
entertainer: null
}
}
render(){
return(
<div className = 'Immediate_Events'>
<header className = 'ImmEventsTitle'>
Upcoming Events
</header>
<div className = 'EventBlock'>
{return this.props.queryEvent(this.props.query).then(() => this.props.queried_events.forEach(function(event){
return ( <div>
<span className = 'EventTitle'>JSON.parse(event["title"])</span>
{this.props.artist_events ?
this.props.artists_events.forEach((entertainer) => {
return <span className = 'ArtistName'>
<span onClick = {this.state.entertainer !== entertainer.name ? this.props.ParseEventsByArtist(entertainer.name, this.props.eventForecast).then(function(){this.setState({artist: entertainer.name})}) : null}>
entertainer.name
</span>
</span>}) :
event.performers.forEach((entertainer) => { return <span className = 'ArtistName'>
<span onClick = {this.state.entertainer !== entertainer.name ? this.props.ParseEventsByArtist(entertainer.name, this.props.eventForecast).then(function(){this.setState({artist: entertainer.name})}) : null}>
entertainer.name
</span>
</span>
})
}
<span className = 'EventHappenstance'>JSON.parse(event["venue"]["name"])</span>
<span className = 'EventAddress'>JSON.parse(event["venue"]["address"]), JSON.parse(event["venue"]["extended_address"])</span>
</div>
)
}))
}
</div>
</div>
)
}
function mapStateToProps(state){
queried_events: state.eventOptions.queried_events
}
export default connect(mapStateToProps, {queryEvent})(EventQueries)
In the browser console, this is what I am getting in return for this particular file: EventQueries.js
Any help would be appreciated. Thanks.

This was a simple mistake. I simply needed to add a return in front of queried_events in the mapStateToProps in order for the function to understand what the this.props.queried_events was referring to.

You need to remove the return statement from here:
<div className = 'EventBlock'>
{return
You're essentially nesting a return inside a return. It's not necessary there.

Related

How to implement `Search box` through `props items` using ReactJs

I want to implement search box from my set of props data .
I tried to follow this article https://dev.to/iam_timsmith/lets-build-a-search-bar-in-react-120j but i guess i m doing some silly mistakes.
any help to correct my mistake would be helpful for me.
//allbook.js
class AllBook extends Component {
constructor(props){
super(props);
this.state = {
search : ""
}
}
updateSearch(e){
this.setState({search: e.target.value.substr(0, 20)});
}
render(){
let filteredBooks = this.props.posts.filter(
(posts) => {
return posts.title.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1;
}
);
return(
<div>
{Object.keys(filteredBooks).length !== 0 ? <h1 className="post-heading">All books</h1> : <h1 className="post-heading">No Books available</h1>} {/*To check if array is empty or not*/}
{Object.keys(filteredBooks).length !== 0 ?
<input className="post-heading" type="text" value={this.state.search} onChange={this.updateSearch.bind(this)}/> : ""}
{/*Arrow function to map each added object*/}
{filteredBooks.map((post) =>(
<div key={post.id}>
{post.editing ? <EditComponent post={post} key={post.id}/> :
<Post key={post.id} post={post}/>}
</div>
))}
</div>
);
}
}
const mapStateToProps = (state) => {
return{
posts: state
}
}
export default connect(mapStateToProps)(AllBook);
Your updated code seems to be pretty close. I think you might experience a problem with using indexOf() though, since that will only find the index of a single-character within a string (title). This would not be good for multi-character searches (like full-words).
Try using .includes() instead so that you can at least search against complete words and titles. It's essentially a better version of .indexOf()
See sandbox for example: https://codesandbox.io/s/silly-currying-3zpvk
Working code:
class AllBook extends Component {
constructor(props){
super(props);
this.state = {
search : ""
}
}
updateSearch(e){
this.setState({search: e.target.value.substr(0, 20)});
}
render(){
let filteredBooks = this.props.posts.filter(
(posts) => {
return posts.title.toLowerCase().includes(this.state.search.toLowerCase());
}
);
return(
<div>
{Object.keys(filteredBooks).length !== 0 ? <h1 className="post-heading">All books</h1> : <h1 className="post-heading">No Books available</h1>} {/*To check if array is empty or not*/}
{Object.keys(filteredBooks).length !== 0 ?
<input className="post-heading" type="text" value={this.state.search} onChange={this.updateSearch.bind(this)}/> : ""}
{/*Arrow function to map each added object*/}
{filteredBooks.map((post) =>(
<div key={post.id}>
{post.editing ? <EditComponent post={post} key={post.id}/> :
<Post key={post.id} post={post}/>}
</div>
))}
</div>
);
}
}
const mapStateToProps = (state) => {
return{
posts: state
}
}
export default connect(mapStateToProps)(AllBook);
Updated code which is workable react search.

How to fix error of hiding and showing <div> in React

I am working on a project and i want to display a hidden <div> below another <div> element using an event handler but when i click the icon that is meant to display the div, the whole page becomes blank
This is image I want:
This is what i get
I have tried to check through the internet for some places where i could get the solution. Well i found something similar to what i had done but the error still happens for me.
class PostItTeaser extends Component {
state = {
postIt: false,
moreIt: false,
}
togglePostIt = e => {
e ? e.preventDefault() : null
this.setState({ postIt: !this.state.postIt })
}
_toggle = e => {
e ? e.preventDefault() : null
this.setState({
moreIt: !this.state.moreIt,
})
}
Child = () => <div className="modal">Hello, World!</div>
render() {
let { postIt } = this.state
let { moreIt } = this.state
let {
type,
group,
disabled,
session: { id, username },
} = this.props
return (
<div>
<div
className="post_it inst"
style={{ marginBottom: type == 'group' && 10 }}
>
<img src={`/users/${id}/avatar.jpg`} alt="Your avatar" />
<div className="post_teaser">
<span
className="p_whats_new"
onClick={disabled ? null : this.togglePostIt}
>
What's new with you, #{username}? #cool
</span>
<span className="m_m_exp" data-tip="More" onClick={this._toggle}>
<MaterialIcon icon="expand_more" />
</span>
</div>
</div>
{moreIt && <Child />}
{postIt && (
<PostIt back={this.togglePostIt} type={type} group={group} />
)}
</div>
)
}
}
From skimming through the code I believe you need to bind the scope, since the function you're calling is using this.setState, it needs this to be the react component, not the event you're listening to:
onClick={this._toggle.bind(this)}
You can also bind the functions scope in the constructor. Or, a less memory performant & ugly way:
onClick={() => { this._toggle(); } }

How to put classname and variables in ternary at Reactjs?

I have different datasets. Some of them have only icon and some of them have images. I want to control the data whether iconurl is null or not in the beginning and then if has icon url I will use FontAwesome if iconurl = null I will use img tag. But my images does not come to screen. Also I have could not bring the name to h3 tag. It looks empty on the screen. I am confused a bit. May you help me please? thank you in advance.
Note: I have already checked some ternary examples in react but they were too basic.
render() {
return (
this.state.diagnoses.map(user =>
<div className={'cat-box-region'}>
<div className={'cat-box-position'}>
<div className={'cat-box'}>
{user.IconUrl ? (<FontAwesomeIcon icon={user.IconUrl} size="3x" className={'icon'}/>) : (<img src={user.ImgUrl} className={'ultrasound-img'}/>)}
<h3>{user.name}</h3>
</div>
</div>
</div>
)
);
}
I solved problem like that :
class DiagnosisBox extends Component {
static propTypes = {};
state = {
diagnoses: [],
diagnosesWithImg: [],
diagnosesWithIcon: []
};
componentDidMount() {
fetch('http://localhost:51210/api/service')
.then(response => {
return response.json();
}).then(diagnoses => {
this.setState({
diagnoses,
});
console.log(diagnoses);
})
}
render() {
this.state.diagnoses.map(stateData =>
stateData.iconUrl ? this.state.diagnosesWithIcon.push(stateData)
: this.state.diagnosesWithImg.push(stateData)
);
return (
<div className={'cat-box-region'}>
{this.state.diagnosesWithIcon.map(data =>
<div key={data.id} className={'cat-box-position'}>
<div className={'cat-box'}>
<FontAwesomeIcon icon={data.iconUrl} size="3x" className={'icon'} />
<h3>{data.diagnosisName}</h3>
</div>
</div>
)}
{this.state.diagnosesWithImg.map(data =>
<div key={data.id} className={'cat-box-position'}>
<div className={'cat-box'}>
<img src={data.ImgUrl} className={'ultrasound-img'}/>
<h3>{data.diagnosisName}</h3>
</div>
</div>
)}
</div>
);
}
}
export default DiagnosisBox;

React - How to show relative div when mouse hover on a html tag?

Below is my code...
<ul className="no-style board__list">
{Object.keys(today.books).map(function(id) {
var refBook = today.books[id][0];
return (
<li key={refBook._id} className="board__list-item">
<div className="container flexrow">
<div className="flexrow__fit-2">{refBook.book_no}</div>
<div className="flexrow__org">
<span className="board__icon-wrap">
{refBook.memo
? (<i className="fa fa-flag" style={{color:"#F9AB9F"}}></i>)
: null
}
</span>
{refBooking.memo
? (<div className="memo_dialog">{refBook.memo}</div>)
: null
}
</div>
</div>
</li>
);
})}
</ul>
I have a object books array and I create a fa-flag icon for each book.
What I want is to show different memo dialog when mouse hover on each flag icon.
I know how to do it with query but how can I do this in react way not using jquery?
I'm not sure what are you trying to achieve but this example might be useful for you
class Book extends React.Component {
constructor(props){
super(props);
this.handleOver = this.handleOver.bind(this);
}
handleOver(name){
this.props.over(this.props.name)
}
render(){
return <div onMouseOver={this.handleOver}>{this.props.name}</div>
}
}
class BookList extends React.Component {
constructor(props){
super(props);
this.mouseOver = this.mouseOver.bind(this);
this.state = {
books: ['hello', 'amazing', 'world'],
memo: ''
}
}
mouseOver(name){
this.setState({memo: name})
}
render(){
const bookList = this.state.books.map((book, index)=>{
return <Book key={index} name={book} over={this.mouseOver}/>
});
return <div>
{bookList}
<hr/>
<div>{this.state.memo}</div>
</div>
}
}
React.render(<BookList />, document.getElementById('container'));
Also fiddle example.
I hope it will help you. Thanks
I suggest you to use isHovered state variable, to store hover state.
We are displaying some component(in your case it would be dialog box), if isHovered is true and hide it when this variable is false.
When we will hover on link element, we will trigger handleEnter function to set isHovered variable to true.
Similarly, when we are moving cursor out of link element, we are triggering handleLeave function to set isHovered variable to false.
Example:
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
isHovered: false,
};
}
handleEnter() {
this.setState({
isHovered: true
});
}
handleLeave() {
this.setState({
isHovered: false
});
}
render() {
return (
<div>
<a
onMouseEnter={this.handleEnter.bind(this)}
onMouseLeave={this.handleLeave.bind(this)}
>Link</a>
{this.state.isHovered ? (
<div className="box">A component</div>
) : (
<div />
)}
</div>
);
}
}
Also, you can see demo at CodePen.

ReactJS if prop exists

at the moment I am getting an error with React because I am mapping an array of objects from a REST end point and some of the objects in the array don't have certain props.
An example is that some of my objects have another object within them called imagesand some don't. When my React component tries to render the objects without the images I am left with an error undefined prop.
Here is my component that renders my prop:
const VehicleDetail = (props) => {
return (
<div className={"col-flex-md-3 col-flex-sm-4 col-flex-xs-6 col-flex-media-query vehicle-item " + props.vehicle.brand.name} data-value={props.vehicle.brand.name}>
<div className="vehicle-container">
<img src={"https://s3-eu-west-1.amazonaws.com/pulman-vw-images/uploads/images/thumbnails/" + props.vehicle.offers[0].image.name} />
<h4 className="vehicle-title">
{props.vehicle.model.name}
</h4>
<div className="row-flex">
<div className="col-flex-xs-12 btn-container">
Learn More
</div>
</div>
</div>
</div>
);
};
So as you can see I have an img element with a prop of props.vehicle.offers[0].image.name however this fails as some of my objects don't have this object available.
So far I have tried adding an inline conditional just to see if the object existed first however this failed with an error:
<img src={"https://s3-eu-west-1.amazonaws.com/pulman-vw-images/uploads/images/thumbnails/" + {if (typeof props.vehicle.offers[0].image.name == "object") { props.vehicle.offers[0].image.name }}} />
Here is my component that iterates over each object and renders them to my VehicleDetail component:
// Vehicle List Component
import VehicleDetail from './vehicle-detail.js';
// Create our component
const VehicleList = (props) => {
// Just add props.vehicle to access API data instead of static
const RenderedVehicles = props.vehicles.map(vehicle =>
<VehicleDetail key={vehicle.slug} vehicle={vehicle} />
);
return (
<div className="row-flex center-xs">
{RenderedVehicles}
{console.log(props.brandSelect)}
</div>
);
};
Any idea what the best practice in React JS is to do this? Thanks
Check the length of offers before rendering.
{props.vehicle.offers.length > 0 ? (
<img src={url + props.vehicle.offers[0].image.name} />
) : null}
I'd do it like this. In your vehicle component declare a variable that would hold the thumbnail url.
const VehicleDetail = (props) => {
let vehicleThumbnail = '';
if (props.vehicle.offers[0].image && props.vehicle.offers[0].image.name) {
vehicleThumbnail = props.vehicle.offers[0].image.name;
}
return (
<div className={"col-flex-md-3 col-flex-sm-4 col-flex-xs-6 col-flex-media-query vehicle-item " + props.vehicle.brand.name} data-value={props.vehicle.brand.name}>
<div className="vehicle-container">
<img src={vehicleThumbnail} />
<h4 className="vehicle-title">
{props.vehicle.model.name}
</h4>
<div className="row-flex">
<div className="col-flex-xs-12 btn-container">
Learn More
</div>
</div>
</div>
</div>
);
};
I'd also do the same for the other props.
The normal case of props.vehicle.offers[0] may looks like this:
{
image: {
name: 'hello'
}
}
So, you can use props.vehicle.offers[0].image.name without any error.
But some cases are:
{
anotherProperty: {
}
}
props.vehicle.offers[0].image is null, so props.vehicle.offers[0].image.name equals to null.name, which throw the error.
A simple way to solve the problem is something like this:
{ props.vehicle.offers[0].image && <img src={"https://s3-eu-west-1.amazonaws.com/pulman-vw-images/uploads/images/thumbnails/" + props.vehicle.offers[0].image.name} /> }
If props.vehicle.offers[0].image is null, the statement after && will not be execute, and return nothing to render.
So, it render img element when props.vehicle.offers[0].image is not null, preventing the error.

Categories

Resources