Home > other >  Change the value props of a component in react
Change the value props of a component in react

Time:08-21

Is it possible to change the props of a already rendered component in react?

export default function Example() {
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false)
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const value= "bla123"
  const triggerSidebar = (value :any) => {
    setSidebarOpen(true)
    value = "123bla"
  }
  return (
    <>
    <Header/>
    <Sidebar status={value} sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} />
    <Button onClick={() => triggerSidebar()}>
      Click me!
    </Button>

I try to set a new status to the Sidebar on the Click Event, but "123bla" wont be rendered

CodePudding user response:

Very close but you're missing a state

export default function Example() {
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  // const value= "bla123"
  const [value, setValue] = useState("bla123");
  const triggerSidebar = (value :any) => {
    setSidebarOpen(true);
    //value = "123bla"
    setValue("123bla");
  };
  return (
    <>
    <Header/>
    <Sidebar status={value} sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} />
    <Button onClick={() => triggerSidebar()}>
      Click me!
    </Button>

CodePudding user response:

Use useState to get a reactive value, it'll update view after set it

export default function Example() {
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false)
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [value, setValue] = useState('bla123')

  const triggerSidebar = (value: any) => {
    setSidebarOpen(true)
    setValue('123bla') // Update state and view
  }
  return (
    <>
      <Header />
      <Sidebar status={value} sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} />
      <Button onClick={() => triggerSidebar()}>Click me!</Button>
    </>
  )
}

  • Related