Home > other >  React- Use state to apply css style
React- Use state to apply css style

Time:04-02

I have a style function where I am applying style to search input box

const SearchInputWrapper = styled.div`
  height: auto;
  width: 100%;
  box-sizing: border-box;
  padding: 0;
  align-self: stretch;
  word-break: break-word;
  background-color: grey;
  #tags-container {
    height: 20px;
    text-overflow: unset;
    white-space: unset;
    :focus {
      height: auto !important;
    }
  }
`;
const SearchBarView = forwardRef((props, ref) => {
    const [pinned, setPinned] = useState(false);
   return return (
<>
  <SearchInputWrapper>
    <SearchInputBox
      iconMarginTop="6px"
      minHeight="30px"
      setSearchPinned={setSearchPinned}
      isPinnable
      isSearchPinned={pinned}
      fontSize="14px"
      backgroundColor="transparent"
      pinUIHeightThreshold={40}
      iconSize="15px"
    >
      
    </SearchInputBox>
  </SearchInputWrapper>
}

I would like to apply the height to be auto also when the pinned state is true. I have defined the state in a different function.

How do I access the state within the SearchInputWrapper ? Ideally I would like to do something like :

${state.pinned ? `
      height: auto !important;
    `: `
      height: 20px;
    `}  

But it won't capture the state as its outside the SearchBarView function. Please help!

CodePudding user response:

https://codesandbox.io/s/exciting-wood-2v1395?file=/src/App.js

You can put the style inside the component declaration and take height out of the top declaration like this:

const SearchBarView = forwardRef((props, ref) => {
    const [pinned, setPinned] = useState(false);
   return return (
<>
  <SearchInputWrapper style={{
    height : pinned ? "auto !important" : "20px"
    }}>
    <SearchInputBox
      iconMarginTop="6px"
      minHeight="30px"
      setSearchPinned={setSearchPinned}
      isPinnable
      isSearchPinned={pinned}
      fontSize="14px"
      backgroundColor="transparent"
      pinUIHeightThreshold={40}
      iconSize="15px"
    >
      
    </SearchInputBox>
  </SearchInputWrapper>
}
  • Related