简体   繁体   中英

Changing the parent of a component in React.js

I have a situation where i have a component (say a timer ticking down) . On firing a specific trigger say a button click or page scroll, i want to change the Wrapper Component of <Timer/> component from the div with id dummyWrapper to div with id newParent . Is there any React specific way to achieve this?

By using portals, the element is mounted and unmounted thereby losing the current "state" of the timer.

Using document.getElementById( newParent ).appendChild(TimerWrapper) seems to work, but im not sure if this is a good approach.

Sample DOM Structure:

<App>
<div id="newParent"/>
<Child />
</App>

const Child = () => {
return <div> <div id="dummyWrapper"> <Timer/>  </div>
}

You need to hoist the state from the child component into the parent.

With react you need to move away from direct dom manipulation using document.getElementById, jQuery, etc. The single source of truth for your app needs to exist solely in react.

const App = () => {
  const [timerAdded, setTimerAdded] = useState(false)
  return (
    <>
      <div id="newParent">
        {
          timerAdded && <TimerWrapper />
        }
      </div>
      <Child setTimerAdded={setTimerAdded} />
    <>
  )
}

const Child = ({setTimerAdded}) => {
  return <div> <div id="dummyWrapper" onClick={setTimerAdded}> <Timer/>  </div>
}
const Timer = () => { return <span>Tick Tock </span>}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM