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() {

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

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

    function accessMethod() {

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

Add your own answers!

Related Questions

NGINX gives 502 error from browsers but not from Postman

1  Asked on October 13, 2020 by knguyen


Python Pandas cumsum with shift of n

1  Asked on October 10, 2020 by gonzalo-polo


How to read only half a byte from a binary file at a time in C?

2  Asked on October 9, 2020 by nguyenvivian


Failed to install laravel/jetstream on laravel 8

2  Asked on October 8, 2020 by vldcndn


liquibase roll back with spring boot

1  Asked on October 7, 2020 by user1999453


How to change the order of jquery events?

0  Asked on October 2, 2020 by turqay-umudzade


How to == async axios value

0  Asked on September 30, 2020 by jessica-bulldog


Is there a way to set variable methods in Python?

1  Asked on September 30, 2020 by defarm


How to pull data from an array using SQL

1  Asked on September 29, 2020 by sarah


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP