Paul
Paul

Reputation: 4430

React js pass a function this.state context

I have the following function in a file:

helpers.js:

export const returnStateElement = (...elements) => {
  console.log("returnStateElement",this,elements)
  const copy = Object.assign({}, this);
  return elements.reduce((obj, key) => ({ ...obj, [key]: copy[key] }), {});
};

index.js:

import { validateEmail, returnStateElement } from '../../helpers'
...
constructor(props) {
    super(props);
    this.state = {
      email: "[email protected]",
    };
  }
...
handleSubmit = () => {
    const dataSender = this.state.returnStateElement("email");
    console.log("handleSubmit",dataSender)
}

I would like to do that by doing such a thing:

this.state.returnStateElement("email")

passed as this state, this.state is I would return the values which are contained as function arguments.

Link: codesandbox

Upvotes: 0

Views: 114

Answers (1)

quirky purple
quirky purple

Reputation: 2219

You need to bind the context to the function. Here is a working snack showing how you might do that in the constructor

https://snack.expo.io/Sy8J3fyGL

And the code

import * as React from 'react';
import {Button, TouchableOpacity, Text, View, StyleSheet } from 'react-native';

const returnStateElement = (currentState, ...elements) => {
  const copy = Object.assign({}, currentState);
  return elements.reduce((obj, key) => ({ ...obj, [key]: copy[key] }), {});
};

export default class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      email: '[email protected]'
    }

    this.returnStateElement = (...elements) => returnStateElement(this.state, ...elements);
  }

  render() {
    return (
      <View style={styles.container}>
       <TouchableOpacity onPress={() => alert(JSON.stringify(this.returnStateElement('email', 'pass')))}>
       <Text style={styles.paragraph}>Press here</Text>
       </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Upvotes: 1

Related Questions