Thursday, June 25, 2015

Lists And Keys in Reactjs



In JavaScript, we can easily define and load the array but in reactJs it is bit difficult because you must care about key and states. so, let’s start..
Here, we are doing one basic blog app.
I hope you know the basic architecture of reactJs.
I can start with create-react-app blog
start with App.js
First we create the object post:
const posts= [
{id: 1, title: “Hello World”, content: “Welcome to learning React!” },
{id: 2, title: “Installation”, content: “You can install react from npm” },
]
then we create function Blog inside the render().
Inside the Blog() I will create to variables like overview and content
Here overview include summary of my blog and content include the detail of my post.
const overview = (
<ul>
{props.posts.map((post) =>
<li>
{post.title}
</li>
)}
</ul>
And now content code lookalike this.
const content = props.posts.map((post) =>
<div key = {post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
There is return() returns the overview and content to the Blog() like this.
return(
<div>
{overview}
<hr/>
{content}
</div>
);
Note: This return() is the function Blog() return function not a App component’s return function.
Here, how my render() look like…
render() {
function Blog(props){
const overview = (
<ul>
{props.posts.map((post) =>
<li>
{post.title}
</li>
)}
</ul>
);
const content = props.posts.map((post) =>
<div key = {post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return(
<div>
{overview}
<hr/>
{content}
</div>
);
}
const posts= [
{id: 1, title: “Hello World”, content: “Welcome to learning React!” },
{id: 2, title: “Installation”, content: “You can install react from npm” },
]
Now, it’s time to return Blog() to the render(). so, it can get the data.
return (
<div>
<Blog posts= {posts} />
</div>
);
finally, App.js look like this..
import React, { Component } from ‘react’;
import logo from ‘./logo.svg’;
import ‘./App.css’;
class App extends Component {
render() {
function Blog(props){
const overview = (
<ul>
{props.posts.map((post) =>
<li>
{post.title}
</li>
)}
</ul>
);
const content = props.posts.map((post) =>
<div key = {post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return(
<div>
{overview}
<hr/>
{content}
</div>
);
}
const posts= [
{id: 1, title: “Hello World”, content: “Welcome to learning React!” },
{id: 2, title: “Installation”, content: “You can install react from npm” },
]
return (
<div>
<Blog posts= {posts} />
</div>
);
}
}
export default App;
In index.js , we Render the component.
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import ‘./index.css’;
import App from ‘./App’;
import registerServiceWorker from ‘./registerServiceWorker’;
ReactDOM.render(<App />, document.getElementById(‘root’));
registerServiceWorker();
So, finally we can get output like this after run the app by npm start….
Output:
Hello World
Installation

Hello World
Welcome to learning React!
Installation
You can install react from npm