How to use context in Svelte?
Let's think of a scenario where we have three components A, B, and C. We want to define a variable or an object in Component A
. And we want, It to be accessible from Component C
. In our previous articles, we discussed different methods to pass the props data to the parent component. In this article, we'll discuss the context method in svelte.
Svelte passes parent component data to its child components. The getContext
and setContext
functions can access associated data with a key on the context. Changes made to context values are only valid for the current child component. Parent component values are intact.
Let's say a user logged in and, in another component, we want to show the user details (the email and login status in another child component). In this, it is a good idea to use the Context API instead of passing the props. (Probably a store will be more appropriate but, it is out of scope for this article).
In the App.svelte
<script>
import { setContext } from 'svelte'
const userDetails = { username: 'abc@example.com', islogin: 'yes' };
setContext('user-details', userDetails )
import ContextComponent from "./ContextComponent.svelte";
</script>
<main>
<p> Context Example. </p>
<hr/>
<div>
<br />
<ContextComponent />
</div>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
If we check the setContext{}
function, we'll see something similar export declare function setContext<T>(key: any, context: T): void;
The setContext
function accept two arguments:
- Context Key
- Value or variable or an object that we want to send all of the child application components.
setContext('user-details', userDetails )
we set the context key as user-details
and pass userDetails
object as second argument.
Svelte provides getContext
function to retrieve the setContext
key. Create another component ContextComponent.svelte
and add the following code:
<script>
import { getContext } from 'svelte'
const userDetails = getContext('user-details')
</script>
<div>
<div>
<strong>User Name:</strong> { userDetails.username }
</div>
<div>
<strong>User Login Status:</strong> { userDetails.islogin }
</div>
</div>
export declare function getContext<T>(key: any): T;
how the getContext function is defined in svelte.
It only accepts one argument (key). That we defined in our App
component( `user-details` ) in this case.
If you go to the web page, you'll see:
Thats all about Context in Svelte. See you in the next article.