Why is the inline style not applied?

Viewed 115

I have a inline style in jsx for a conditional class (class that is added and removed based on a condition). But the inline style is not applied for some reason.

function App() {
  const [date , setDate] = useState('')
  const [circleBoolean, setCircleBoolean] = useState(false);
  let random_number;
  useEffect(() => {
    const interval = setInterval(() => {
      doThings()
    }, 2000);
    return () => clearInterval(interval);
  }, [circleBoolean]);

  function doThings() {
    setCircleBoolean(!circleBoolean);
    setDate(moment().format('MMMM Do YYYY, h:mm:ss a')) ;
    random_number = Math.random()*100;
    console.log("cirlce boolean :" + circleBoolean)
  }

  console.log("cirlce boolean outside:" + circleBoolean)


  return (
    <div className="App">
      <div className="bg">
        <div style={{top:random_number+"%"} , {left:random_number+"%"}}  className={circleBoolean ? "circle" : ""}   />
        <div className="card">
          <p className="card-info">{date}</p>
        </div>
      </div>
    </div>
  );
}

<div style={{top:random_number+"%"} , {left:random_number+"%"}} className={circleBoolean ? "circle" : ""} , here the top and left styles are not applied when circle class is added.

2 Answers

You are writing inline styles the wrong way.

Check out the code below

<div style={{
    top:`${random_number}%`,
    left:`${random_number}%`
}}  className={circleBoolean ? "circle" : ""}   />

Style properties like top, left should all be in one object which should be passed to the HTML element's style attribute.

You have to use random_number as a state to update changes to UI, also the way you write inline style is incorrect. Check my sample: https://codesandbox.io/s/ancient-wood-6143r?file=/src/App.js. Note that I use marginTop, marginLeft instead of top,left to reflect the change in style (not sure about your intention of using top,left).

Related