We also need a tab component as the navigation 's subcomponents.
render() {
const { active, updatePointer } = this.props;
const style = classnames("label", {
"active": active,
});
return (
<Link className={style} to={this.props.path}>{this.props.label}</Link>
);
}
This component will receive an initial prop to get its style : active
.
a function to update its style : updatePointer
.
props.path
for assigned to get other URL.
props.label
to assigned its text.
classname
is a very useful tool to update style , when active
is true , the active class will be merged into the component and update the style.
Now there is the updatePointer
function from its father component :
updatePointer() {
this.setPointerState(this.props.path
.map(item => item.path)
.indexOf(location.pathname));
}
//To compare the truely path and the props.path
for geting the index.
setPointerState(idx) {
if (idx !== this.state.index) {
this.setState({
index: idx,
}, this.updatePointers(idx));
}
}
//To preventing it updated automatically loopy ( yeah I mean it will loop) , we must compare the previous state and the index. the after setState
run the updatePointers
, which I have mentioned in the last article.
Now there is an extremely important part . keep your attention here .
componentDidMount() {
this.setTimetoUpdate();
}
setTimetoUpdate() {
return setTimeout(this.props.updatePointer, 2000);
}
We should have a clock to delay it update its initial style. if too fast to get its real position
and width
.
And the important part have not over .
componentDidUpdate() {
this.props.updatePointer();
}
Why we need this function ?
Let 's see the state: when the URL have changed , because of the Link
component the component will update automatically once . and the componentDidUpdate
will be run once . if have no this function , the component will be updated just when the user clicks it .In the beginning, I have not mentioned how important it's , but in some situations, the user will go back when he scanning the page, then the pointer will not place the right place (it just doesn't know the URL have changed).
there is the ending , don't forget this defaultProps
:
Tab.defaultProps = {
active: false,
};