Grisha Pushkov
Grisha Pushkov

Reputation: 83

React functional props

Let me show you an example first:

<List hidden={this.state.hideList} />

For this case I would like hidden prop to function in the following way: if value is true – hide component or show otherwise. And List shouldn't be aware about this prop.

I don't know much about React internals, but it seems to be possible. We just need to extended React.Component class. Maybe extending globally with all functional props isn't good idea, but having something like this at the top would be nice:

import { ReactComponent } from 'react'
import extend, { hidden } from 'react-functional-props'
const Component = extend(ReactComponent, hidden)

It reminds me directives in Angular.js, but here we are able to combine them.

Upvotes: 0

Views: 45

Answers (1)

Tr1et
Tr1et

Reputation: 895

You can just return null or undefined in the render method to prevent it from rendering, or use a conditional class to hide it, like this:

return !this.state.hideList && <List />;

And about the

react-functional-props

In React, you can use higher order component (HOC) to achieve what you need, for example:

const Hideable = Component => (props) => {
  const { isHidden, ...otherProps } = props;

  return !isHidden && (<Component {...otherProps} />);
};

const HideableList = Hideable(List);

...

return (
  <div>
    <HideableList isHidden={this.state.hideList} /> // The isHidden props is handled by the HOC
  </div>
);

But for a simple use case like this, I think just handle the hide and show in the parent component is much more clearer.

Upvotes: 2

Related Questions