Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
ReactJS by Example - Building Modern Web Applications with React

You're reading from   ReactJS by Example - Building Modern Web Applications with React Building Modern Web Applications with React

Arrow left icon
Product type Paperback
Published in Apr 2016
Publisher Packt
ISBN-13 9781785289644
Length 280 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Vipul A M Vipul A M
Author Profile Icon Vipul A M
Vipul A M
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Getting Started with React FREE CHAPTER 2. JSX in Depth 3. Data Flow and Life Cycle Events 4. Composite Dynamic Components and Forms 5. Mixins and the DOM 6. React on the Server 7. React Addons 8. Performance of React Apps 9. React Router and Data Models 10. Animation 11. React Tools 12. Flux 13. Redux and React Index

Passing data to components

"Do we define our data and everything else in the render method?"

"I was just getting to that. Our component should not contain this information. The information should be passed as a parameter to it."

"React allows us to pass the JavaScript objects to components. These objects would be passed when we call the React.render method and create an instance of the <App> component. The following is how we can pass objects to it:"

React.render(<App title='Recent  Changes'/>, document.body);

"Notice how are using the <App/> syntax here, instead of createElement. As I mentioned previously, we can create elements from our components and represent them using JSX as done earlier."

React.render(React.createElement(App), document.body)

"The preceding code becomes the following:"

React.render(<App/>, document.body)

"That looks even more cleaner", said Shawn.

"As you can see, we are passing the title for our table as the title parameter, followed by the contents of the title. React makes this data passed to the component as something called props. The props, short for properties, are a component's configuration options that are passed to the component when initializing it."

"These props are just plain JavaScript objects. They are made accessible to us within our component via the this.props method. Let's try accessing this from the render method, as follows:"

…
  render: function(){
   console.log(this.props.title);
  }
…

"That should start logging the title that we passed to the component to the console."

"Now, let's try to abstract the headings as well as the JSON data out of the render method and start passing them to the component, as follows:"

       var data = [{ "when": "2 minutes ago",
                           "who": "Jill Dupre",
                           "description": "Created new account"
                         },
                         ….
                        }];  
var headings = ['When', 'Who', 'Description']
<App headings = {headings} data = {data} />

"There. We pulled the data out of the render method and are now passing it to our component."

"We defined the dynamic headers for our table that we will start using in the component."

"Here the curly braces, used to pass the parameters to our component, are used to specify the JavaScript expressions that will be evaluated and then used as attribute values."

"For example, the preceding JSX code will get translated into JavaScript by React, as follows:"

React.createElement(App, { headings: headings, data: data });

"We will revisit props later. However, right now, let's move on to complete our component."

"Now, using the passed data and headings via props, we need to generate the table structure in the app's render method."

"Let's generate the headings first, as follows:"

var App = React.createClass({

  render: function(){
      var headings = this.props.headings.map(function(heading) {
          return(<th>
                 {heading}
                 </th>);
      });
  }
});

"Notice, how we are using this.props.headings to access the passed information about headings. Now let's create rows of the table similar to what we were doing earlier:"

var App = React.createClass({

  render: function(){
      var headings = this.props.headings.map(function(heading) {
          return(<th>
                 {heading}
                 </th>);
      });

      var rows = this.props.data.map(function(change) {
          return(<tr>
                   <td> { change.when } </td>
                   <td> { change.who } </td>
                   <td> { change.description } </td>
                 </tr>);
      });
  }
});

"Finally, let's put the headings and rows together in our table."

var App = React.createClass({

  render: function(){
      var headings = this.props.headings.map(function(heading) {
          return(<th>
                 {heading}
                 </th>);
      });

      var rows = this.props.data.map(function(change) {
          return(<tr>
                   <td> {change.when} </td>
                   <td> {change.who} </td>
                   <td> {change.description} </td>
                 </tr>);
      });

      return(<table>
               {headings}
               {rows}
             </table>);
  }
});

React.render(<App headings = {headings} data = {data} />,
                      document.body);

"The table is now displayed with the passed dynamic headers and JSON data."

"The headings can be changed to ["Last change at", "By Author", "Summary"] and the table in our view will get updated automatically."

"Alright, Shawn, go ahead and add a title to our table. Make sure to pass it from the props."

"Ok," said Shawn.

"Now, the render method will be changed to the following:"

…
 return <div>
               <h1>
                 {this.props.title}
               </h1>
               <table>
                 <thead>
                   {headings}
                 </thead>  
                 {rows} 
                </table>
            </div>
…

"While the call to React.render will change to the following:"

var title =  'Recent Changes';
React.render(<App headings={headings} data={data} title={title}/>, document.body);

"Awesome. You are starting to get a hang of it. Let's see how this looks in completion shall we?"

var App = React.createClass({
  render: function(){
      var headings = this.props.headings.map(function(heading) {
          return(<th>
                 {heading}
                 </th>);
      });

  var rows = this.props.data.map(function(row){
  return  <tr>
     <td>{row.when}</td>
     <td>{row.who}</td>
     <td>{row.description}</td>
   </tr>

  })
 return <div><h1>{this.props.title}</h1><table>
 <thead>
{headings}
 </thead>  
{rows} 
 </table></div>
  }
});
  var data = [{ "when": "2 minutes ago",
              "who": "Jill Dupre",
              "description": "Created new account"
            },
            {
              "when": "1 hour ago",
              "who": "Lose White",
              "description": "Added fist chapter"
            },
            {
              "when": "2 hours ago",
              "who": "Jordan Whash",
              "description": "Created new account"
            }];

var headings = ["Last updated at", "By Author", "Summary"]
var title = "Recent Changes";
React.render(<App headings={headings} data={data} title={title}/>, document.body);

"We should again start seeing something as follows:"

Passing data to components

"Here we have it, Shawn. Our very first component using React!", said Mike.

"This looks amazing. I can't wait to try out more things in React!", exclaimed Shawn.

You have been reading a chapter from
ReactJS by Example - Building Modern Web Applications with React
Published in: Apr 2016
Publisher: Packt
ISBN-13: 9781785289644
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime