Take variable parameter Javascript/React function

Asked

Viewed 1,286 times

0

How do I take a function parameter and use it to pick up a variable? For example, in this code:

import React, { Component } from 'react';

export default class Home extends Component {
  state = {
    name: 'joao',
    age: 18
  }
  set = (s, v) => {
    this.setState({s: v})
  }
  get = (s) => {
    return this.state.s;
  }
  render() {
    return(
      <div>
        <button onClick={() => this.set('name', 'maria')}>Mudar Nome</button>
        <button onClick={() => this.set('age', 20)}>Mudar Idade</button>
        {this.get('name')}
        {this.get('age')}
      </div>
    );
    };
}

I wanted to pass the get('name') and the get do something like: Return this.state.name; But it does not return this, it seems that it uses only the s

How do you do that? What’s the name of it? (this code I made just for example)

2 answers

1


If you change your method set for

set = (s, v) => {
    this.setState({
        [s]: v
    })
}

(note the [] involving the key s) you must achieve your goal. This is called Computed Property Names

  • Exactly what I needed, but it only worked on set, no get gave problem: . /src/pages/home/index.js Line 19: Parsing error: Unexpected token 17 | } 18 | get = (s) => { > 19 | Return this.state. [s]; | 20 | } 21 | // template 22 | render() {

  • How did you write the get?

  • https://hastebin.com/oqerulexol.js

0

In your case you can do it like this:

class Home extends React.Component {
  constructor() {
    super();
    this.state = {
      name: "João",
      age: 18
    };
  }

  handleName = e => {
    this.setState({
      name: e.target.dataset.name
    });
  };

  handleAge = e => {
    this.setState({
      age: e.target.dataset.age
    });
  };

  render() {
    return (
      <div>
        <button onClick={this.handleName} data-name="Marcelo">
          Mudar Nome
        </button>
        <button onClick={this.handleAge} data-age="22">
          Mudar Idade
        </button>
        {this.state.name}
        {this.state.age}
      </div>
    );
  }
}

React.render(<Home />, document.getElementById("root"));

I updated the code.

  • Thanks for the reply diego, I gave you a +&#Xa { if(s == 'name') Return this.state.name; Else if(s == 'age') Return this.state.age; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.