Jose Jose - 1 month ago 7
Javascript Question

React: setting state in container from within functional component

So I have a container component which renders a functional component along with some other JSX. I am trying to change the state in that container from a button click that is occurring from inside that functional component. However I haven't found a good article on tackling this yet and I run into the problem of

this.setState() is not a function
or I completely break the current tab by trying to
trigger a setState call during a render
(more or less).

Here's some sample code to illustrate what I mean:

class TestComponent extends Component {
render() {
<div>
<FunctionalComponent close={(type) => this.setState({ property: type })} />
</div>
}
};


Functional component:

const FunctionalComponent = (props) => {
return (
<button onClick={props.close('stringvalue')}>Click to setState</button>
);
};


Have also tried by creating a separate function inside the container and calling
this.setState()
from there, but the problem persists. Is this a context problem?

Answer

A little more idiomatic . . .

class TestComponent extends Component {
  constructor(props) {
    super(props);
    this.onClose = this.onClose.bind(this);
  }

  onClose(property) {
    this.setState({ property })
  }

  render() {
    return (
      <div>
        <FunctionalComponent close={this.onClose} />
      </div>
    )
  }
};

const FunctionalComponent = ({ close }) => {
  return (
    <button onClick={close.bind(null, 'stringvalue')}>Click to setState</button>
  );
};