C
C
cyberlain2021-11-22 12:07:04
JavaScript
cyberlain, 2021-11-22 12:07:04

How to change the global state on click on the generated link?

There is such a cat in which the names and refs of links are taken from the api and a list of these links is created

import React from "react";
import App from "../App";

class Nav extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            contents: []
        }
    }
    sayHello() {
        alert('Hello!');
    }
    componentDidMount() {
        fetch("https://api", {
            headers: {
                Authorization: `Bearer key`
            }
        })
            .then(response => response.json())
            .then(data => {
                console.log(data)
                this.setState({
                    contents: data.records
                })
            })
            .catch(err => {
                console.log(err);
            });

    }

    render() {
        const {contents} = this.state
        return (
            <nav className="nav">
                <ul>
                    {this.state.contents.map(item => <MenuItem  key={item.id} {...item.fields} /> )}
                </ul>
            </nav>
        )
    }
}
export default Nav


const MenuItem = ({ Href, Title }) => (
    <li>
        <a href={'/' + Href}>{Title}</a>
    </li>
)


how now when I click on the link I need to change the sectionTitle property in App.jsx?
(well, please, in general, evaluate whether the connection to the api and the generation of the list are done correctly)
constructor(props) {
        super(props)
        this.state = {
            sectionTitle: 'Добро пожаловать',
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2021-11-22
@karminski

Hello. In general, code is code. It's trendy/modern now to use React on hooks rather than as class components. According to the state - in your code there is no global state as such at all. You can include Redux (the simplest) or, if you're into hooks, use the useReducer + useContext bundle.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question