Hi I want to create a global variable in react but I would like to avoid it, so I created a component and want to store string data in it such as below:
export default function settings() {
const [stringData, setStringData] = useState("");
I want this state to concactnate input string. For example
setStringData("I am ");
setStringData(" a ");
setStringData("robot.");
When I retrieve stringData I want it to be printed as
I am
a
robot.
How do I do this ?
When you calling setStringData it is the same as though you just assign a value to a variable, e.g. stingData = 'asdf' so if you need to concatenate strings you need to add the current value and the string you want to add, below you can find an example.
const [stringData, setStringData] = useState("");
setStringData(stringData + "Some Sting To Append!");
UPD: Based on the comments, showing an example with some listener.
const [stringData, setStringData] = useState("");
const addString = () => setStringData(stringData + " Clicked!");
return (<button onClick={addString}> Add Text </button>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With