Kreitzo Kreitzo - 3 months ago 13
React JSX Question

React: Invalid prop type Link when using JSX

Below is a dummied-down version of what I'm doing

When clicking on the Skip button I'm getting info from a random "page" then using this.state to show it.

import React from "react"
import { Link } from 'react-router'

const MyComponent = React.createClass({
getRandomPage () {
var pages = [
{
link: "/1_page_one",
title: "title one",
description: "Description1"
},
{
link: "/2_page_two",
title: "title Two",
description: "Description2"
},
{
link: "/3_page_three",
title: "title three",
description: "Description3"
}
]
var randomNum = Math.floor(Math.random() * pages.length);
this.setState({page: pages[randomNum]});
},
getInitialState () {
return {
page: "hi"
}
},
render () {
console.log(this.state.page.link);
return (
<div>
<div>
<li><Link to="/1_page_one"><button type="submit">To Page</button></Link></li>
<li><button onClick={this.getRandomPage} type="submit">Skip</button></li>
</div>
</div>
<div>
<h1>{this.state.page.title}</h1>
<h2>Description</h2>
<div>
{this.state.page.description}
</div>
</div>
);
}
});

export default MyComponent;


Everything seems to work fine except when I try to change

<li><Link to="/1_page_one"><button type="submit">To Page</button></Link></li>


to

<li><Link to={this.state.page.link}><button type="submit">To Page</button></Link></li>


I get an error saying :

main.js:8715 Warning: Failed prop type: Invalid prop `to` supplied to `Link`.
in Link (created by ChallengeBoxes)
in ChallengeBoxes (created by MainContent)
in div (created by MainContent)
in MainContent (created by RouterContext)
in div (created by App)
in App (created by RouterContext)
in RouterContext (created by Router)
in Router


But when checking to see what the value is with


console.log(this.state.page.link);


The link in state is a correct string such as "/1_page_one"?

What's going wrong?

Answer

this.setState({page: pages[randomNum]}) in getRandomPage() isn't called when the component is mounted. So, the initial render will hit the error when this.state.page.link is undefined yet, but as soon as you hit the button, your this.state.page.link has something in it.

Change your initial state maybe:

getInitialState () {
    return {
      page: {
         title: 'something...',
         link: '/1_page_one',
         description: 'something...'
      }
    }
  }