< Previous: What are React Props?   Next: How to Write if/else Conditional Statements in JSX >

Generating Random Values for Our Page

Our Detail component is now executing code to render the text that gets passed to it as props, but it could easily render other valid ES6 code too. To demonstrate this, let's pull in the Chance library, which generates realistic-looking random data.

In your terminal window, run this command:

npm install --save chance

You were probably still running Webpack Dev Server in there, but that's OK - press Ctrl+C to quit that, then run the npm command above. Once that's finished you can restart Webpack Dev Server again by running webpack-dev-server.

The Chance library generates realistic-looking random data, which means it can generate random first names, last names, sentences of text, social security numbers and so on – this makes it a good test case for printing out some information. To use it you need to import the library into Detail.js, like this:

src/pages/Detail.js

import Chance from 'chance';

You can then generate random first names inside the render() method like this:

src/pages/Detail.js

return <p>Hello, {chance.first()}!</p>;

Just to make sure you're following along, here's how your Detail.js file should look once these changes are made:

src/pages/Detail.js

import React from 'react';
import Chance from 'chance';

class Detail extends React.Component {
    render() {
        return <p>Hello, {chance.first()}!</p>;
    }
}

export default Detail;

If you save that file and look back in your web browser you'll see "Hello, Emma!" or similar appear, and you can hit refresh in your browser to see a different name.

So you can see we're literally calling the first() method in the Chance library right there while rendering, and I hope it's clear that putting code into braces like this is very powerful indeed.

But there's a catch, and it's a big one. In fact, it's a catch so big that fisherman will tell tall tales about it for years to come…

Buy the book for $10

Get the complete, unabridged Hacking with React e-book and take your learning to the next level - includes a 45-day no questions asked money back guarantee!

If this was helpful, please take a moment to tell others about Hacking with React by tweeting about it!

< Previous: What are React Props?   Next: How to Write if/else Conditional Statements in JSX >

Copyright ©2016 Paul Hudson. Follow me: @twostraws.