TransWikia.com

Changing the state of a Component using a method in that Component from an external button

Stack Overflow Asked by Rick Gove on December 18, 2020

I have a component that does 3 things:

  1. displays "Sup?" from state var data
  2. Has a button which "Says be formal" which sets state to ‘Hello, how are you?’ using a method called sayHello
  3. Has a button which "Says be casual" which sets state to ‘Sup?’ using a method called sayHelloCas

Outside of this component I have a button which I would like to be able to change the state inside the Component using the Components SayHelloCas function.

Is this possible? I’ve tried to use useRef to no success…

import React, { useRef, useState } from 'react';

export default function App() {
    const myRef = useRef();

    const WithMethod = () => {
        let [data, setData] = useState(['Sup?']);

        function sayHello() {
            setData(['Hello, how are you?']);
        }

        function sayHelloCas() {
            setData(['Sup?']);
        }

        function display() {
            return data.map((a, b) => {
                console.log(a, b);
                return <h1 key={b}>{a}</h1>;
            });
        }

        return (
            <div
                style={{
                    display: 'flex',
                    border: '2px dotted dodgerblue',
                    padding: '2rem',
                    margin: '2rem',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                }}
            >
                <button onClick={sayHello}>Be formal!</button>
                <ul>{display()}</ul>
                <button onClick={sayHelloCas}>Be casual!</button>
            </div>
        );
    };

    function accessMethod() {
        myRef.current.sayHello();
    }

    return (
        <div>
            <WithMethod ref={myRef} />
            <button onClick={accessMethod}>Be formal (external)!</button>
        </div>
    );
}

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP