2

I'd like to set overflow-y: hidden for the html selector (not an element) based on whether a React class component state variable is true. Is that possible?

2
  • Yes, that is possible. you can do something like className={this.state.hidden ? "class to show" : " " } Commented Nov 23, 2019 at 6:04
  • You can create a style object and apply it the same way. style={this.state.hidden ? {"overflowY": "hidden"} : {} } Commented Nov 23, 2019 at 6:17

4 Answers 4

1

If you mean you want to apply the overflow-y to the actual HTML tag then putting this code in the render worked for me

...
render() {
  let html = document.querySelector('html');
  this.state.test === "test" ? html.style.overflowY = "hidden" : html.style.overflowY = "visible";
  return (
   ....
  )
};
Sign up to request clarification or add additional context in comments.

Comments

0

You can do

function MyComponent() {
    // Set your state somehow
    const [something, setSomething] = useState(initialState)
    // Use it in your className`
    return <div className={!!something && 'class-name'} />
}

If you have multiple class names to work with, a popular package is (aptly named) classnames. You might use it like so:

import cx from 'classnames'


function MyComponent() {
    const [something, setSomething] = useState(initialState)

    return <div className={cx({
        'some-class' : something // if this is truthy, 'some-class' gets applie
    })} />
}

Comments

0

Yes, It's possible. You can do this.

function App() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const htmlSelector = document.querySelector("html");
    htmlSelector.style.overflowY = visible ? "unset" : "hidden";
  }, [visible]);

  return (
    <button onClick={() => setVisible(prevState => !prevState)}>
      Toggle overflow
    </button>
  );
}

See the full example on CodeSandbox

Comments

0

You can use the style property to set inline CSS:

<div style={{ overflowY: hide ? 'hidden' : 'auto' }}>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.