Below is the sandbox link -
https://codesandbox.io/s/tabs-component-bkjr1?file=/src/App.js
I want to have a smooth behaviour on the background when user selects any of the option from the tab. The background changes abruptly as of now. I want to have similar behaviour as of tabs in material-ui as the indicator moves from one selected option to the other.
Edit-1: I want to implement the slide behaviour on the background.
Here it is, in Vue 3, which is pretty similar to React. Should give you an idea about what you need to do. If anything is not clear, please ask.
const { createApp, reactive, onMounted, watch, toRefs } = Vue;
createApp({
setup() {
const state = reactive({
items: ['All Posts', 'Public', 'Private'],
activeIndex: 0,
menuRef: null,
menuItemRefs: [],
floaterStyle: {}
});
const updateFloater = () => {
const e = state.menuItemRefs[state.activeIndex]?.getBoundingClientRect();
const m = state.menuRef?.getBoundingClientRect();
if (e && m) {
state.floaterStyle = {
inset: `${
e.top - m.top}px ${
m.right - e.right}px ${
m.bottom - e.bottom}px ${
e.left - m.left}px`
}
}
};
onMounted(updateFloater);
watch(() => state.activeIndex, updateFloater);
return toRefs(state);
}
}).mount('#app')
.menu {
padding: 1rem;
display: flex;
position: relative;
}
.menu div:not(.floater) {
padding: 1rem;
cursor: pointer;
transition: color .1s linear;
}
.menu .floater {
background-color: red;
position: absolute;
z-index: -1;
transition: inset .3s cubic-bezier(.4,0,.2,1);
border-radius: 25px;
}
.menu .active {
color: white;
}
<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
<div id="app">
<div class="menu" ref="menuRef">
<div class="floater" :style="floaterStyle"></div>
<div v-for="(item, key) in items" v-text="item"
:class="{active: key === activeIndex}"
:ref="el => el ? menuItemRefs.push(el): void 0"
@click="activeIndex = key"></div>
</div>
</div>
Update: Same thing, in React.
I strongly advise you to do the "translation" to React yourself. You'll learn more and you'll end up understanding what's going on in DOM, under the hood.