Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native pass a function as props to child component

I am trying to pass a function from one component to its child, in this case Posts.js maps through each post and adds a prop called changeState. But It does not appear to be working.

The code for Posts.js

import Post from "./post"

export default function posts() {

  const posts = [<arrayOfPosts>];

  const [favoritesChanged, setFavoritesChanged] = useState(1);

  const changeState = () => {
    setFavoritesChanged(Math.random());
  }

  useEffect(() => {
    console.log("favorites changed");
  }, [favoritesChanged])

  return (
    {posts.map((post) => {
      <Post changeState={changeState} key={post.id} />
    }
  )
}

Then in the post.js file we have:

const Post = ({ changeState }) => {
  console.log("change state: ", changeState);
  return (
    <View>
      <TouchableOpacity onPress={changeState}>
        <Text>Click here to test.</Text>
      </TouchableOpacity>
      <Text>{post.title}</Text>
    </View>
  )
}

export default Post

But the press action doesn't fire the changeState function and where it is being console.logged it says undefined. Why is this not working?

like image 854
Starfs Avatar asked May 04 '26 19:05

Starfs


1 Answers

You are missing returning the Post component JSX in the .map callback:

return (
  {posts.map((post) => {
    return <Post changeState={changeState} key={post.id} post={post} />
  })}
);

or using an implicit arrow function return:

return (
  {posts.map((post) => (
    <Post changeState={changeState} key={post.id} post={post} />
  ))}
);

Ensure you are destructuring all the props you need that are passed:

const Post = ({ changeState, post }) => {
  return (
    <View>
      <TouchableOpacity onPress={changeState}>
        <Text>Click here to test.</Text>
      </TouchableOpacity>
      <Text>{post.title}</Text>
    </View>
  )
};
like image 139
Drew Reese Avatar answered May 06 '26 12:05

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!