Home > Mobile >  How to get string inside react-bootstrap's textarea and send to function on button-click?
How to get string inside react-bootstrap's textarea and send to function on button-click?

Time:05-31

I have the following react-bootstrap code;

<Form>
  <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
    <Form.Label>Example textarea</Form.Label>
    <Form.Control as="textarea" rows={3} />
  </Form.Group>
</Form>
    
<Button
  variant="outline-primary"
  size="lg"
  active
  onClick={() => wave(TextAreaString)}
>
  Wave at Me
</Button>

The webpage looks like this;

enter image description here

When the button is clicked, I would like the function wave(textarea_string) to run. textarea_string is the string inside the textarea.

I am using React-bootstrap v2.4 and React v18

CodePudding user response:

  • Define a state to hold the string value with the useState hook
  • Define onChange handler to save the changed string value with the set-function of useState hook
  • Read the value from state in your wave function

.

export default function App() {
  const wave = (text) => console.log(text);
  const [value, setValue] = useState("");
  const onChange = (event) => setValue(event.target.value);
  return (
    <div className="m-3">
      <Form>
        <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
          <Form.Label>Example textarea</Form.Label>
          <Form.Control
            as="textarea"
            rows={3}
            value={value}
            onChange={onChange}
          />
        </Form.Group>
      </Form>

      <Button
        variant="outline-primary"
        size="lg"
        active
        onClick={() => wave(value)}
      >
        Wave at Me
      </Button>
    </div>
  );
}

https://codesandbox.io/s/determined-bassi-h85x27

  • Related