why react props are passed undefined to the child component?
Because you have async request and when Header is being mounted you don't have this data yet.
Try this:
render(){
const article = this.state.article
const team = this.state.team
if(!article && !article.date && !article.author) {
return null;
}
if(!team) {
return null;
}
return(
<div>
<Header
teamData={ team }
date={ article.date }
author={ article.author }
/>
{ JSON.stringify(article,team) }
</div>
)
}
Inside the componentWillMount you are using axios which returns a promise and is asynchronous. The problem is that you are rendering the <Header/>
before the data is fetched from the API. To Avoid this you can update your render
function like this.
function render() {
let article = this.state.article;
let team = this.state.team;
return (
<div>
{team.length ? (
<Header teamData={team} date={article.date} author={article.author} />
) : (
'Loading Data...'
)}
{JSON.stringify(article, team)}
</div>
);
}
First of all, @Evghenii 's answer is correct.
Here's the more smart and recommended approach to handle conditional rendering.
You can use Higher Order Components to handle conditional rendering in reactjs.
For more details: Higher Order Components with Conditional Rendering in React.