Home > Back-end >  Send selected text to another div in react JS using onSelect event?
Send selected text to another div in react JS using onSelect event?

Time:10-21

I have a two div I want to send selected text to another div using onSelect event? Right now entire para sending to another div but I want to send just selected text. How can I do this?

Demo:- https://codesandbox.io/s/selected-text-send-to-another-div-using-onselect-0ccnrn?file=/src/App.js

My Code:-

import React from "react";
import { Box, Grid, TextField, Typography } from "@material-ui/core";
import { useState } from "react";

const SendSelectedText = () => {
    const [label1, setlabel1]=useState('');
    const [para, setPara]=useState('This is Old Para');
   const handleClick = () => {
    setlabel1(para);
  };
  return (
    <>
      <Box className="sendSelectedTextPage">
        <Grid container spacing={3}>
          <Grid item xl={6} lg={6} md={6}>
            <textarea onSelect={handleClick}>{para}</textarea>
          </Grid>
          <Grid item xl={6} lg={6} md={6}>
            <TextField
              variant="outlined"
              size="small"
              label="Label One"
              value={label1}
              multiline
              rows={3}
              className="sendSelectedTextPageInput"
            />
          </Grid>
        </Grid>
      </Box>
    </>
  );
};

export default SendSelectedText;

Thanks for your support!

CodePudding user response:

All you need is use window.getSelection(). Here is solution

import React from "react";
import { Box, Grid, TextField, Typography } from "@material-ui/core";
import { useState } from "react";

const SendSelectedText = () => {
  const [label1, setlabel1] = useState("");
  const [para, setPara] = useState("This is Old Para");
  const handleMouseUp = () => {
    setlabel1(window.getSelection().toString()); // setting up label1 value 
  };
  return (
    <>
      <Box className="sendSelectedTextPage">
        <Grid container spacing={3}>
          <Grid item xl={6} lg={6} md={6}>
            // changed event to onm ouseUp 
            <textarea onm ouseUp={handleMouseUp}>{para}</textarea>
          </Grid>
          <Grid item xl={6} lg={6} md={6}>
            <TextField
              variant="outlined"
              size="small"
              label="Label One"
              value={label1}
              multiline
              rows={3}
              className="sendSelectedTextPageInput"
            />
          </Grid>
        </Grid>
      </Box>
    </>
  );
};

export default SendSelectedText;

Sandboxlink

CodePudding user response:

You have to use the selection

const handleClick = (e) => {
  setlabel1(
    e.target.value.substring(e.target.selectionStart, e.target.selectionEnd)
  );
};

or

const handleClick = (e) => {
  setlabel1(
    para.substring(e.target.selectionStart, e.target.selectionEnd)
  );
};

Based on this

sandbox

  • Related