1

this is probably a very basic question. im making a settings page for my site and I need some help.

<Route path="/conversations/settings" render={props => <Setting isNew colorMode=
{props.colorMode} toggleColorMode={props.toggleColorMode}/>}/>

so what I want this to do ideally is when you click a button on the settings page it enables/disables darkmode. In this situation it doesnt. but if I write it like this

<Setting colorMode={props.colorMode} toggleColorMode={props.toggleColorMode}/>

I can actually enable/disable darkmode, but this means the settings page renders on every page of the website which of course, I dont want.

Charlie
  • 115
  • 1
  • 8
  • Assuming you are not using redux, you should use context API. So that the theme is available on every page without having to pass props or worry about renders. In fact the react official context example is based on theming only. https://reactjs.org/docs/context.html – Mohit Singh Jan 26 '22 at 03:25

1 Answers1

0

Since you say that <Setting colorMode={props.colorMode} toggleColorMode={props.toggleColorMode}/> works I'll assume that wherever you are rendering this Setting component that props is in scope and has the prop values you want.

If you are wanting to render Setting on a route and pass other non-route-props though then you are correct to use the render prop to do so. The issue you've now is that you are accessing the passed route props instead of your props object that is in scope. Rename the route props to something other than the props of the outer parent component and spread these into your Setting component if you need them.

<Route
  path="/conversations/settings"
  render={routeProps => (
    <Setting
      {...routeProps} // <-- history, location, & match
      isNew
      colorMode={props.colorMode}             // <-- you props
      toggleColorMode={props.toggleColorMode} // <-- your props
    />
  )}
/>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181