four-eyes
four-eyes

Reputation: 12392

Externalise common functions in various react components

In different components where I use the same functions when it comes to styling or something else. Some of these functions use this.setState({...}); I want to collect all these functions in a common place, so when rewriting them I don't have to rewrite them in all the components, but only on one file. However, I do not know how to write the this.setState({...}); in the functions without loosing its context. Is there a way?

Upvotes: 0

Views: 3073

Answers (1)

Nocebo
Nocebo

Reputation: 2017

I assume you mean exporting one function and call this function in various components while remaining the scope of this

MyExportedFunctions.js:

export function handleChange(value, {target: {name, type}}) {
    this.setState({[name]: value}, () => console.log(this.state));
}

MyComponent.js:

  import {handleChange} from "./MyExportedFunctions";

        class MyComponent extends Component {
            constructor(props) {
                super(props);
                this.handleChange = handleChange.bind(this);

                this.state = {

                };
            }
            ...
     }

Did you mean something like this?

Upvotes: 3

Related Questions