Adding Component's State to a String in React

10,473

You don't need the curly braces unless you're writing JSX. Since your updateFilter() function is just a normal Javascript function, you can write it as:

updateFilter() {
  var newSearch = "Searching" + this.state.var1 + this.state.var2;
  this.setState({
    currentFilter: newSearch
  });
}

Though, FYI, what you'll get for newSearch will be an incoherent "SearchingDogCat" so you may want to rethink your concatenation.

Share:
10,473
lost9123193
Author by

lost9123193

Learning

Updated on June 04, 2022

Comments

  • lost9123193
    lost9123193 over 1 year

    I have a component with the following states:

    class Example extends Component {
      constructor(props) {
        super(props);
        this.state = { 
          var1: "Dog",
          var2: "Cat",
          var3: [20, 40],
          currentFilter:"None"
        };
          this.updateFilter = this.updateFilter.bind(this);
      }
    

    In the update filter function, I want to incorporate all the state properties, but the following syntax does not work:

    updateFilter(){
      var newSearch= "Searching" {this.state.var1} + {this.state.var2}
      this.setState({
        currentFilter: newSearch
      });
    }
    

    Is there a way to incorporate the properties of state into the string variable?

  • lost9123193
    lost9123193 over 7 years
    Thanks! And the example I used is just a very simplified bare bones version of my app, but point taken.