Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REACTJS: Change state in another class

I have two file Reactjs
file1.js

class App extends Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        selection: null
    };

file2.js

class SearchBar extends Component {
InputChange = () => {
    console.log(App.state);
}}

I want to use and change state of class App when using class SearchBar, i imported the file2 to file1. Thank you! My English is not good.

like image 745
Trần Mạnh Cường Avatar asked Aug 29 '26 19:08

Trần Mạnh Cường


1 Answers

This is easy :D you just need to pass in the function that changes the state like so:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data: [],
        selection: null
  };

  changeStuff(paramsIfAny) {
    this.setState(/* whatever you want */);
  }

  render() {
    .....
     <SearchBar changeHandler={this.changeStuff.bind(this)} />
    .....
  }
}

And then on your SearchBar component

class SearchBar extends Component {
InputChange = (params) => {
   this.props.changeHandler(params);
}}

This was really abbreviated code to simplify what I meant. I hope you got how it is done!

like image 151
João Cunha Avatar answered Aug 31 '26 09:08

João Cunha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!