Reputation: 1816
I have an if-else situation, in the else situation I am trying to load data from a Component as well as pass data into it. The code for that is something like this
import React from 'react';
import ReactDom from 'react-dom' ;
//import data from '../data.json';
import { withRouter, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import {FullBlog} from './FullBlog.js'
class Author extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data,
load:false,
content:'',
}
this.loadBlog=this.loadBlog.bind(this);
}
loadBlog(i){
that.setState({
load:true,
})
// this.props.router.history.push('/fullblog');
//window.location='/fullblog'+this.state.data;
browserHistory.push('/fullblog')
}
render(){
if(this.state.load===false){
return(
<div onClick={this.loadBlog.bind(this,this.props.i)} className="box">
<div>{this.props.i}</div>
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
)
}//else{
// //return(<div><FullBlog data={this.state.data}/></div>)
// }
}
}
The function is loadBlog in which I tried to use browserHistory.push() but I don't know how can I pass data into the same and also I get error `'Cannot read property push of undefined.'`
Then, I tried using the Link tag like this
if(this.state.load===false){
return(
<Link to={'/fullblog'+this.props.data}><div onClick={this.loadBlog.bind(this,this.props.i)} className="box">
<div>{this.props.i}</div>
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
</Link>
)
}//else{
// //return(<div><FullBlog data={this.state.data}/></div>)
// }
}
}
For the above, I get error as invalid react element
.
What is the correct way of implementing the same.I am using react-router v4.
Edit:
Updated the code to
<div>
<Link to={'/fullblog/${this.props.data}'}/><div onClick={this.loadBlog.bind(this,this.props.i)} className="box">
<div>{this.props.i}</div>
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
</div>
I get Invariant violation error and React element error for the above.
Upvotes: 0
Views: 581
Reputation: 185
You are returning undefined. You always need to return a React component in the render
method. What you can do is the following, as it's a common pattern:
render(){
let content = (
<p>I'm returning this by default</p>
);
if (this.state.load===false) {
content = (
<div onClick={this.loadBlog.bind(this,this.props.i)} className="box">
<div>{this.props.i}</div>
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
);
}
return content;
}
I would recommend you to use ESLint plus the Airbnb specific configuration. This will help you avoid this kind of errors and use good patterns.
Upvotes: 1
Reputation: 629
You should be returning something in the else part as well. Uncomment, the code from else block.
Upvotes: 1