M
M
maxemga2021-03-12 20:07:39
React
maxemga, 2021-03-12 20:07:39

How to pass a variable from one component to another in an object?

From one Component, I need to change the state of an object in another, I need from a class:

class App extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      arr: [],
      activeModal: false
    }
  }

  render() {
    return (
      <div className='wrapper'>
        <div className='content'>
          <Title></Title>
          {this.state.arr.length === 0 ? <p>No todos!</p> : <TodoList list={this.arr}></TodoList>}
          <Button Click={() => this.setState({activeModal: true})}></Button>
          <ModalWindow active={this.state.activeModal}></ModalWindow>
        </div>
      </div>
    );
  }
}

Change the state of activeModal to false in this class:
class ModalWindow extends React.Component {
    constructor(props) {
        super(props);
        
        this.state = {
            value: '',
            active: this.props.active
        }
    }

    render() {
        return(
            <div className={this.props.active ? "modalOverlay modalOverlayActive" : "modalOverlay"}>
                    <div className='modalWindow'>
                        <div className='modalContent'>
                            <div className='modalClose' onClick={() => this.setState({active: false})}> <p>Close</p> </div>
                            <h1>Введите название</h1>
                            <form>
                                <input placeholder="Название"></input>
                            </form>
                            <Button></Button>
                        </div>        
                    </div>
                </div>
        )
    }
}


But I don’t know how to refer this.setState({active: false})to activeModal in this function, because active is a key, and you can’t write this.props there, I try to assign in state active: this.props.active, but it doesn’t work, how to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shcherbakov, 2021-03-12
@Simply1993

It's a bit vaguely written, but if I understand correctly, I don't know what your problem is.
As an option (perhaps not the best), you can write a handler function in the App class that will set your activeModal to false and pass this function through props to the ModalWindow. Inside it, take the function from props and hang it on onClick in the place you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question