A
A
Andrey2018-02-09 14:19:42
React
Andrey, 2018-02-09 14:19:42

Is it possible to change the state of an external component through props?

Recently I ran into a problem - changing the state through changes in the internal component. I know that it is possible to pass an external function inside the component, which will change via this.setState({ something: input parameter });
Let's say:

// InnerComponent
// Тут код компонента
// Внутри компонента, допустим, на input'e, меняем this.props.text через onChange

Why does react allow us to change, without errors, the state of an external component by simply changing the props? After all, you can change only through this.setState?
// State of App component
this.state = {
    text: 'Hello world'
}

render() {
  return <InnerComponent text={this.state.text} />
}

The specific situation is here. (github)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-02-09
@andrey_koyta

1. If you try to change this.props , you will get an exception:
2. You have the ability to mutate state , but you don't have to.
A good way to manage the state of components is through the parent:

class Example extends Component {
  state = {
    inputValue: '',
  };

  handleChange = e => { 
    const { name, value } = e.target;
    
    this.setState({
      [name]: value,
    });
  };

  render() {
    const { inputValue } = this.state;

    return (
      <Wrapper>
        <input
          name="inputValue"
          value={inputValue}
          onChange={this.handleChange}
        />
        ...
      </Wrapper>
    );
  }

I
Igor, 2018-02-09
@aM-aM

Purely an example, it is possible to make more beautiful.

this.state = {
    text: 'Hello world'
}

handleChangeText = text => {
   this.setState({ text })
}

render() {
  return <InnerComponent handleChangeText={this.handleChangeText} text={this.state.text} />
}

const InnerComponent = ({ handleChangeText }) => {
  return (
    <div onClick={() => handleChangeText('some text')}>text</div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question