0

I have a group of Components that render different parts of the same page. Whenever an action is commited inside one of them, the other ones should be locked (a volatile flag should be propagated through them and trigger a javascript function that disables all elements)

Block Components:

class FirstBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    render() {......}
}
class SecondBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    render() {......}
}

Page Component:

import FirstBlock from 'Components/FirstBlock';
import SecondBlock from 'Components/SecondBlock';

class PageBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    render() {
        return (
            <FirstBlock ... />
            <SecondBlock ... />
        );
    }
}

Any ideas? I'm new to react and any tip will be helpful.

Matheus Simon
  • 668
  • 11
  • 34
  • 2
    If your components are rendered in different places, you can take a look at Redux (https://redux.js.org/), which gives you a clean way to share a state between components. – Sascha Klatt Nov 18 '19 at 21:50

1 Answers1

1

In (very) general terms, pass an event handler into each of your blocks from your parent. When an action is triggered from one of them, deal with this in the parent. If you need to change your behaviour depending on which child raises the action you'll need to have some kind of identifier for each of your children, so that when the handler is called it knows what to do.

class PageBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    onAction = (id)=>{
       // set isVolatile or do whatever you need to do
    }
    render() {
        return (
            <FirstBlock id={firstBlockId} onAction={this.onAction}... />
            <SecondBlock id={secondBlockId} onAction={this.onAction}... />
        );
    }
}


class FirstBlock extends React.Component {
    constructor(props) {
        super(props);
        .......
        }
    }
    onAction = ()=>{
        this.props.onAction(this.props.id)
    }
    render() {......}
}

The principle is to lift your common state (i.e. that something has triggered an action) up to a parent so that the children that need to know about the state can have access to it.

Will Jenkins
  • 9,507
  • 1
  • 27
  • 46