C
C
cyberlain2021-12-28 17:34:29
React
cyberlain, 2021-12-28 17:34:29

How, when clicking on a link in one component, change some value in another?

There is a link in one component with an attribute such as data-title="to start"
How can I get the value of this attribute by clicking and display it in an arbitrary place on the site, in another component?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shsv382, 2021-12-29
@cyberlain

Learn state management. You have a parent component and two child components, one with a button, the other with something to change.

<Parent>
    <Child1><a data-title="на старт" /></Child1>
    <Child2></*что-то для изменения, например param*/></Child2>
</Parent>

the state of the parent should contain the desired parameter that changes on button click, as well as the button click handler function. You pass the handler function as prop to Child1, and the parameter from state to Child2.
class Parent extends React.Component {
    state = {
        naStart: false
    }

    handleClick = (event) => {
        if (event.target.dataTitle === "на старт") {
            this.setState({naStart: true})
        }
    }

    render() {
        return (
            <div>
                <Child1 onClick={this.handleClick} />
                <Child2 param={this.state.naStart} />
            </div>
        )
    }
}

Or learn redux, there is more flexible state management

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question