Passing props to a react component wrapped in withRouter() function

Viewed 23571

I am using React-Router v4 to navigate in my React app. The following is a component wrapped in the withRouter() function to make it able to change route on click:

const LogoName = withRouter(({history, props}) => (
  <h1
    {...props}
    onClick={() => {history.push('/')}}>
    BandMate
  </h1>
));

As you can see I pass the props to the component, which I need in order to change the class of the component. The problem here is that props is undefined in the <LogoName> component. I need to be able to change the class of this component when I click on another component, like this:

<LogoName className={this.state.searchOpen ? "hidden" : ""} />
<div id="search-container">
  <SearchIcon
    onClick={this.handleClick}
    className={this.state.searchOpen ? "active" : ""} />
  <SearchBar className={this.state.searchOpen ? "active" : ""}/>
</div>

Here is how I handle the click. Basically just setting the state.

constructor(){
  super();
  this.state = {
    searchOpen: false
  }
}

handleClick = () => {
  this.setState( {searchOpen: !this.state.searchOpen} );
}

Is there a way for me to pass props to a component that is wrapped inside the withRouter() function or is there a similar way to create a component which has the ability to navigate with React-Router and still receive props?

Thanks in advance.

3 Answers

This worked for me:

import  {withRouter} from 'react-router-dom';
class Login extends React.Component
{
   handleClick=()=>{
      this.props.history.push('/page');
   }
   render()
  {
     return(
          <div>
          .......
            <button onClick={this.handleClick()}>Redirect</button>
          </div>);
  }
}

export default withRouter(({history})=>{
  const classes = useStyles();
    return (
        <Login  history={history} classes={classes} />
    )
});
Related