I want to use textarea input like global state in react. But I have problem in context file

Viewed 81

I need Textarea input-like state in five different components. I want to read that state in component, make calculations and write results back in textarea.

import React, { useState, Component } from "react";

const Context = React.createContext();

export default function App() {
    const [text, setText] = useState("");

    return (
        <Context.Provider value={this.state}>

        <textarea
            className="textarea"
            value={text}
            onChange={(e) => setText(e.target.value)}
            />{this.props.children}

        </Context.Provider>
    );
}

My second component
My second component needs to change the text used global state and write back in textarea. (Function in component1 is just example)


import React, { Component, useContext } from "react";
import { Consumer } from "./context";

class component1 extends Component {
    const toUpperCase = () => {
        setText(text.toUpperCase());
    };

    render() {
        return (
            <Consumer>{value => {
                return

                <textarea
                    className="textarea"
                    value={text}
                    onChange={(e) => setText(e.target.value)}
                />}}
                <button onClick={toUpperCase}>U velika</button>
            </Consumer>
        );
    }
}

export default component1;
0 Answers
Related