Monday, November 29, 2021

Ninja - React Basic 9 - Output Lists

1. create const to hold array of items using useState


steps

1. const [blogs, setBlogs] = useState();

2. Then add array inaside useState();

3. how to create array [{item1},{item2},{item3}]


const [blogs, setBlogs] = useState([

        { title: 'My new website', body: 'lorem ipsum...', author: 'mario', id: 1 },

        { title: 'Welcome party!', body: 'lorem ipsum...', author: 'yoshi', id: 2 },

        { title: 'Web dev top tips', body: 'lorem ipsum...', author: 'mario', id: 3 }

    ]);

Now we have list, array of items

Next how we going to show them in the template

Let's use the same return tag with Home div tag


 return (

        <div className="home">      

        </div>

    );

Inside here using mustache {} , let's try to print


1. use blogs property -> {blogs}

2. then use map method on this --> {blogs.map()}

3. map method will call , call back function for each item , where by each item around we need to return a jsx template. That's gone a go inside parathesis.

4. {blogs.map((() => ()))}

if we format

{blogs.map((() => (

               

           )))}

   

5. for each iteration , we get the access to each item. Let's call it 'blog'

6. So we give it as a input parameter

7. 

{blogs.map(((blog) => (


           )))}


8. On this item, 'blog' as we iterate we get the access to its properties. eg: title, body ...

9. what we plan to put for each item will be next

10. div with classname =  blog-preview . for each item in home page.


 return (

        <div className="home">

            {blogs.map(((blog) => (

                <div className='blog-preview'></div>

            )))}

        </div>

    );

11. When we iterate through items, each root element must have 'key' property. Reat use this to keep track in dom

12. So if we remove or add, data change -  react can keep track of those items


<div className='blog-preview' key={}></div>


13. This must be unique

14. our id will be blog.id


<div className='blog-preview' key={blog.id}></div>


15. Inside this, inside div tag you can do what you need per each item

16. let's output tile in h2 tag and , below that aouthor in para tag


<div className='blog-preview' key={blog.id}>

                    <h2>{blog.title}</h2>

                    <p>Written by {blog.author}</p>

                </div>

Now you should see the output as

---------------------------------


My new website

Written by mario


Welcome party!

Written by yoshi


Web dev top tips

Written by mario


17. For make it pretty, you can add css for preview part inside index.css


No comments:

Post a Comment