I have a React component where the container is yellow, but when its input field is expanded it should be orange.
Using only CSS, it possible to change outer-container
background color when either:
a) input width is expanded, or
b) input has focus?
I tried
.outer-container:focus-within {
background-color: orange;
}
but that does not work because .outer-container:focus-within
is still true after clicking 'x'
button and it does not go back to yellow. The component is imported and can't access the component's JS, but styled-components
package can be used to restyle it. Any ideas?
const {useState} = React;
function Search() {
const [inputClass, setInputClass] = useState('name');
return (
<div className='outer-container'>
<div className='container'>
<input className={inputClass}
onFocus={() => setInputClass('name-expanded')}
onBlur={() => setInputClass('name')}
placeholder="Search" />
<button className='close'>
X
</button>
</div>
</div>
)
}
ReactDOM.render( <Search />, document.getElementById('root') );
.outer-container {
display: flex;
position: relative;
width: max-content;
background-color: yellow;
padding: 5px;
}
.outer-container:focus-within {
background-color: orange;
}
.container {
display: flex;
position: relative;
width: max-content;
height: 30px;
align-items: center;
background: gray;
border-radius: 16px;
padding-left: 16px;
padding-right: 16px;
}
.name {
min-width: 70px;
width: 70px;
outline: none;
}
.name-expanded {
min-width: 70px;
width: 150px;
outline: none;
}
.close {
position: absolute;
left: calc(100% - 30px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<div id="root"></div>