In previous article we learned about props and how to declare function props and read only props. In this article we will learn how to call parent function from child component and child function from parent component. These functionality could be achieved by using function props and read only props.

Calling parent function from child component

Let’s first see how to call parent function from child. We know that we can pass a function as props to the child component. It means when the child accesses the prop variable, it will run the parent function. For example, suppose we have a component child.svelte –

<script>
  export let functionProp = () => {}
</script>

<p>
  I am child component
  and I will run either
  parent function or default
  function -
  <strong>{functionProp()}</strong>
</p>

We declared a simple function prop, functionProp. Now parent component can pass it’s function to this prop which will get called in this child.

<script>
  import Child from './Child'

  function parentFunction(){
    return 'I was called in parent';
  }
</script>

<Child functionProp={() => parentFunction()} />

You may also call the function in javascript. It is not necessary that you need to call the function in html blocks –

<script>
  export let functionProp = () => {}

  let callParentFunction = functionProp();
</script>

<p>Here we called the parent function in JS - {callParentFunction}</p>

Get this example running in live demo below.

Calling child function from parent component

To call the child function from parent, you will need reference. This is usually done using read only props. Not only functions, you can access the variables of child component too. Let’s take an example. Consider a component, Child2.svelte –

<script>
  export function childFunction(){
    return 'I got called in child component'
  }
  export const childProp = 'I am child variable';
</script>

<p>
  Child Component Printing -<br />
  Variable - 
  <strong>{childProp}</strong><br />
  Function - 
  <strong>{childFunction()}</strong>
</p>

Now we can call the function from parent component using bind:this –

<script>
  import Child2 from './Child2'

  let referenceVariable;

</script>

<Child2 bind:this={referenceVariable} />
<p>
 Showing child variables in parent<br />
 variable - 
 {referenceVariable && referenceVariable.childProp}<br />
 function - 
 {referenceVariable && referenceVariable.childFunction()}
</p>

You will find this example in live demo.

Β Β Β Β Tweet this to help others

Live Demo

If demo doesn’t load on this page then use this link – Codesandbox demo.

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles