0

I have project in ReactJS in that I have 3 types of different views to show data. For that I have 3 different component.

I have one parent component in which I have one button called Rotate and three options two change view.

My requirement is I need to set visibility of Rotate button based on view types like for ViewType1 rotate button should be visible and for other types of views rotate button should be hidden.

Below is my code:

Parent Component

class ParentView extends Component {
  constructor(props) {
    super(props);

    this.state = {
       isViewType1: true
    };
    this.setRotateButtonVisibility = this.setRotateButtonVisibility.bind(this);
}
setRotateButtonVisibility(isType1) {
   this.setState({isViewType1 : isType1});
}
render() {
   return(
     {this.state.isViewType1 && (
        <button id="btnRotate" className="btn btn-default">Rotate</button>)
     }
   <Switch>
          <Route
            exact
            path="/project/:projectID"
            render={() => (
            <Viewtype1/>
            )}
          />

          <Route
            exact
            path="/project/:projectID/ukeyview"
            render={() => (
              <Viewtype2/>
            )}
          />
          <Route
            exact
            path="/project/:projectID/proxystructureview"
            render={() => (
              <Viewtype3/>
            )}
          />

     </Switch>
 )}

So, how to call setRotateButtonVisibility() function based on view types?

OR

How to set state based on view types?

I have tried callBackFunc of child component but it is not allowing to change state.

I have tried following code also:

<Route 
   exact
   path="/project/:view
   {...this.setRotateButtonVisibility(false)}
   render={() => (
     <Viewtype3/>
   )}
/>

but nothing is working properly.

Mehul Patel
  • 1,084
  • 2
  • 12
  • 28

1 Answers1

0

You can pass the function down to the child in the render() method of the Route.

<Route 
   exact
   path="/project/:projectId
   render={() => (
     <Viewtype1 setRotateButtonVisibility={(isType1) => this.setRotateButtonVisibility(isType1)} />
   )}
 />

This would mean the method is accessible inside the child react component using props: this.props.setRotateVisibility(false)

You need to capitalise the definitions of component names. So use Viewtype1 not viewtype1 or else React will assume it is a HTML tag and not a Component. See this post: ReactJS component names must begin with capital letters?

TPHughes
  • 1,437
  • 11
  • 13
  • Thanks for your answer but it is also not working. It is Viewtype1 only by mistake I wrote in small letter in my question. – Mehul Patel May 18 '18 at 09:51
  • @MD's sorry you need to pass the parameters of the method to the arrow function. I've updated my answer. Let me know if you still have issues. – TPHughes May 23 '18 at 14:21