0

Parent element (Board) creates list of children and passes them method to access this list, like this:

export default class Board extends React.Component {
    constructor(props) {
        super(props);

        this.getList = this.getList.bind(this);

        const nodes = this.props.data.map(item => (
            <BoardItem key={item.id} next={item.next} accessSiblings={this.getList} />
        ));

        this.state = {data: this.props.data, nodes: nodes}
    }

    getList() {
        return this.state.nodes;
    }

    render() {

        return (
            <div>
                {this.state.nodes}
            </div>
        );
    } }

Then I call update() method and receive this list, filter it and correctly get the required object:

update() {
    console.log(this.props.accessSiblings().find(x => x.key == this.props.next));
}

However it returns Symbol(react.element), and I am trying to get such properties as "offsetTop", "offsetHeight" of already rendered element.

Basically, I want to call an event in one element that gets some DOM properties of sibling element(e.g. offsetTop) and changes the state of this sibling.

Is this the correct approach? It feels very hacky and doesn't work at the moment.

redwinter
  • 241
  • 4
  • 12

1 Answers1

1

You need to use "refs" (see also: how to access a dom element in react).

However, you should avoid working with DOM objects, if possible.

You do need a ref for accessing offsetTop etc., but apart from that you should not pass DOM or ReactElements, but you should only work with state (like "plain javascript" objects) as far as possible, and then render ReactElements (JSX, like <BoardItem ...) as the last step, and never care about DOM elements (React does it for you).

It is also usually not necessary to store ReactElements in variables or state, I suggest to try if you can focus a little bit more on state, and understand JSX more as a way to view the state.

kca
  • 4,856
  • 1
  • 20
  • 41