React.js props issue

64 views Asked by At

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.

1

There are 1 answers

0
Drew Reese On

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
    />
  )}
/>