-
Notifications
You must be signed in to change notification settings - Fork 55
Inject history into a deep component
Josh Thomas edited this page Jul 25, 2018
·
4 revisions
Sometimes you want to access history deep into a component tree. Thankfully we have a way
for you to access history without need to drill the prop all the way down. This is by using
injectHistory
. This function accepts a component and then passes history as a prop.
Note that currently you must have an attribute with the @Element()
decorator.
import { Component, Element, Prop } from '@stencil/core';
import { RouterHistory, LocationSegments, injectHistory } from '@stencil/router';
@Component({
tag: 'test-deep-component'
})
export class TestDeepComponent {
@Element() el: HTMLStencilElement;
@Prop() history: RouterHistory;
@Prop() location: LocationSegments;
@Watch('location')
locationChanged(newValue: LocationSegments, oldValue: LocationSegments) {
console.log('The new location info is: ', newValue);
console.log('The old location info is: ', oldValue);
}
render() {
return (
<div>
<button onClick={() => this.history.push('/')}> Back Home</button>
</div>
);
}
}
injectHistory(TestDeepComponent);