.search
{
position: relative;
width: 60px;
height: 60px;
background: #fff;
border-radius: 60px;
transition: 0.5s;
box-shadow: 0 0 0 5px #2573ef;
overflow: hidden;
}
.search.active
{
width: 360px;
}
.search .icon
{
/* ... */
}
<body>
<div class="search">
<div class="icon"></div>
<div class="input">
<input type="text" placeholder="search" id="mysearch"/>
</div>
<span class="clear" onclick="document.getElementById('mysearch').value=''"></span>
</div>
<script>
const icon = document.querySelector('.icon');
const search = document.querySelector('.search');
icon.onclick = function(){
search.classList.toggle('active')
}
</script>
</body>
Backgroud:
we can change the dom style with the toggle in pure html. as this example , i change the width of searchbar by click event, code as search.classList.toggle('active').
the click event will add a toggle to the class , and the html will match the css .search/.search.active style . but this not work in react ,and is there some approaches to fix it ?
export default function SearchBar() {
const searchRef = useRef(null);
const handleClick = () => {
searchRef.current.classList.toggle('active');
};
return (
<div className={styles.search} ref={searchRef} onClick={handleClick}>
<div className={styles.icon}></div>
<div className={styles.input}>
<input type="text" placeholder="search" id="mysearch" />
</div>
<span className={styles.clear} ></span>
</div>
)
}
.search
{
position: relative;
width: 60px;
height: 60px;
background: #fff;
border-radius: 60px;
transition: 0.5s;
box-shadow: 0 0 0 2px #2573ef;
overflow: hidden;
}
.search.active
{
width: 360px !important;
}
/*more ...*/
I know saving classname with state('search'/'search-acitve') will resove it .
i want to know react can't deal the problem like pure html/css ? it is a simple way .