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>
);
}
1 Asked on October 13, 2020 by knguyen
1 Asked on October 11, 2020 by user12344
3 Asked on October 11, 2020 by reizo
1 Asked on October 10, 2020 by gonzalo-polo
2 Asked on October 9, 2020 by nguyenvivian
0 Asked on October 8, 2020 by paul-martnez-llerena
2 Asked on October 8, 2020 by vldcndn
1 Asked on October 7, 2020 by solar
1 Asked on October 7, 2020 by theoriginof3
1 Asked on October 7, 2020 by user1999453
3 Asked on October 7, 2020 by deitch
2 Asked on October 6, 2020 by raj-endla
0 Asked on October 6, 2020 by madara
1 Asked on October 3, 2020 by singh
0 Asked on October 2, 2020 by turqay-umudzade
3 Asked on October 1, 2020 by pythoncreator
2 Asked on October 1, 2020 by user716255
1 Asked on September 30, 2020 by defarm
Get help from others!
Recent Answers
Recent Questions
© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP