Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert Class Component to Functional Component in React

I have to convert this class based to functional component

class Main extends Components{
  constructor(){
    super()
    this.state = {
      posts:[
      {
        id:"0",
        description:"abc",
        imageLink:"https.xyz"
      },
      {
        id:"1",
      description:"abc",
      imageLink:"https.xyz"
      }
    ]
    }
  }
  render(){
    return
    <>
    <Photowall posts={this.state.posts}/>
    </>
  }
}

And i have done like in functional

posts = [
      {
        id:"0",
        description:"abc",
        imageLink:"https.xyz"
      },
      {
        id:"1",
      description:"abc",
      imageLink:"https.xyz"
      }
    ]

function Main() {
  const [post, setPost] = useState('posts');
  return (

    <>
    <Header title={"Photowall"} />
    <Photowall posts = {posts}/>
    
    
    </>
  )
}

first i put posts in an array then useState to this posts. I want to call the posts from this useState not from outside like as it already like.
posts = [....]
and then
<Photowall post = {posts}/>
But error facing error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Based on your first example your component should look like this, with the default value of posts in the useState

import React, { useState } from "react"

const Main = () => {
    const [posts, setPosts] = useState([
        {
            id:"0",
            description:"abc",
            imageLink:"https.xyz"
        },
        {
            id:"1",
            description:"abc",
            imageLink:"https.xyz"
        }
    ])

    return (
        <>
            <Header title={"Photowall"} />
            <Photowall posts = {posts}/>
        </>
    )
}

export default Main

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading