Stack Overflow Asked by Rick Gove on December 18, 2020
I have a component that does 3 things:
data
sayHello
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>
);
}
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP