I am a beginner in JSX and I need to use lifecycles to prevent some bug when loading an editor from primereact.
However, to make this example more simple, I want to update some string value after initialization and see it in my view.
This is my attempt:
let displayText = '<div>Hello World!</div>';
useEffect(() => {
displayText = '<div>Bye World!</div>;
}, []);
return (<div>{displayText}</div>)
When I run this, I only see "Hello World!". But I expected to see "Bye World", since the variable got updated. What happened here? And how can I achieve this?
If you want an update to cause a render, you can't just assign a variable. A render is triggered after a prop change or a state change. Try converting your variable to a state:
const [displayText, setDisplayText] = useState('<div>Hello World!</div>');
useEffect(() => {
setDisplayText('<div>Bye World!</div>);
}, []);
return (<div>{displayText}</div>)
That way, after the first render, the effect will trigger, the state will change, and it will render again with the new value.
useState documentation: https://reactjs.org/docs/hooks-reference.html#usestate
Also, you will render the string <div>Hello World!</div>, not a HTML div element.