0

I want to control all states in the child components from app.js. Because when I post the state object to the API, I want all changes to send.

import React, {Component} from 'react'
import Navigation from './navigation'
import View from './view'

class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            all: {}
        }
    }

    render() {
        return (
            <div>
                <div className="app">
                    <Navigation />
                    <div className="editable">
                        {this.props.children}
                    </div>
                    <View />
                </div>
            </div>
        )
    }
}

export default App

And the other components are connecting with the router. So I want to fill in this.state.all from the root children data.

It's one of root components

import React, {Component} from 'react'

class Image extends Component {
    constructor(props) {
        super(props)
        this.state = {
            imageWidthBar: 64,
            imageHeightBar: 64
        }
        this.handleInput = this.handleInput.bind(this)
    }

    handleInput(event) {
        this.setState({
            [event.target.name]: event.target.value
        })
    }

    render() {
        return (
            <div className="block">
                <div className="block__row">
                    <span>Image Width</span>
                    <input type="number" name="imageWidthBar" value={this.state.imageWidthBar} onChange={this.handleInput} />
                    <input type="range" name="imageWidthBar" min="0" max="240" step="16" value={this.state.imageWidthBar} onChange={this.handleInput} />
                </div>
                <div className="block__row">
                    <span>Image Height</span>
                    <input type="number" name="imageHeightBar" value={this.state.imageHeightBar} onChange={this.handleInput} />
                    <input type="range" name="imageHeightBar" min="0" max="240" step="16" value={this.state.imageHeightBar} onChange={this.handleInput} />
                </div>
            </div>
        )
    }
}

export default Image

What do you suggest I do?

1 Answers1

0

in Parent

...
handleImageData(data){
   this.setState({ all: data })
}
...
<div className="editable">
       {React.cloneElement(this.props.children, {  
            handleImageData: this.props.handleImageData.bind(this)
       })}
</div>

in Child

handleInput(event) {
        this.setState({
            [event.target.name]: event.target.value
        })
        this.props.handleImageData(event.target.value)
    }

But it is not the most correct solution, as you will sent this props to all your child components. For this task, it seems to me better to use store from redux

Also check this

Cold Sun
  • 1
  • 2