Let’s say we have three components, A, B, and C, and we want to define a variable or object in Component A
, but we also want it to be accessible from Component C
.
In this shot, we’ll discuss the context
method in Svelte.
getContext
and setContext
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 remain intact.
Let’s say a user logs in and we want to show the user details (the email and login status) in another component. In this scenario, we’ll want to use the Context
API instead of passing the props.
<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>
setContext
functionIf we check the setContext{}
function, we’ll see something similar to export declare function setContext<T>(key: any, context: T): void
;.
The setContext
function accept two arguments:
In the code above, we set the context key as user-details
and pass userDetails
object as the second argument.
getContext
functionSvelte provides the 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>
We define the getContext
function as export declare function getContext<T>(key: any): T;
in Svelte.
The getContext
function only accepts one argument (key). In this case, we define the key in our App
component (user-details
).
If you go to the web page, it should look like the image below.
RELATED TAGS
CONTRIBUTOR
View all Courses