I am trying to pass data from a parent to a child component. However, the data I am trying to pass keeps printing out as blank in the child component. My code:
In Profile.js
(Parent component)
<template> <div class="container"> <profile-form :user ="user"></profile-form> </div> </template> <script> import ProfileForm from './ProfileForm' module.exports = { data: function () { return { user: '' } }, methods: { getCurrentUser: function () { var self = this auth.getCurrentUser(function(person) { self.user = person }) }, } </script>
In ProfileForm.js
(Child component)
<template> <div class="container"> <h1>Profile Form Component</h1> </div> </template> <script> module.exports = { created: function () { console.log('user data from parent component:') console.log(this.user) //prints out an empty string }, } </script>
Note - my user
is loaded via my getCurrentUser()
method... Can someone help?
Thanks in advance!
component' you need to define the props passed in the child component. you need to call getCurrentUser() when the parent component initialises.
To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .
Embed the child component to the parent component. Pass the props to the child component as an argument while embedding it to the parent component. In the child component, access the data variable value by writing the name or variable only.
To pass data via props, you have to declare them in child component:
module.exports = { props: ['user'], created: function () { console.log('user data from parent component:') console.log(this.user) //prints out an empty string } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With