Home > database >  How to change color of text in text area using button in react function
How to change color of text in text area using button in react function

Time:12-04

`` hi everyone, I want to take color as input and then change the color of text according to it but it's not working can anybody help me.

import React, {useState} from 'react'

export default function Textform(props) {

//this is function
const newColor =()=>{
      const x = document.getElementById("mybox")
      let newc =color;
    if(x.style.color==="black"){
       x.style.color = setcolor(newc)
    }
    else{
        x.style.color = "black"
    }
    }

const changeColor =(event)=>{
  setcolor(event.target.value);
}

const onChange =(event)=>{
    setText(event.target.value);
}

const [text, setText] = useState("");
const [color, setcolor] = useState("")

return (
    <>
  

//text area input
<div className="mb-3">
    <textarea className="form-control" value={text} onChange={onChange} placeholder="Enter text "  name="" id="mybox"  rows="8"></textarea>
    </div>

//our color choice input
<div className="mb-3">
    <textarea className="form-control" value={color} onChange={changeColor} placeholder="Enter your color choice" name="" id="mybox"  rows="3"></textarea>
    </div>

//this is my button
<button className="btn btn-primary mx-1" onClick={newColor}> Change Color</button>

 </>
  )
}

I tried to create a text Area which take text as input and another text Area which take color as input and then created a button. when we press the button, it will change the color of text as per our choice. but I am going wrong in implementing this logic.

CodePudding user response:

Ideally you shouldn't be using native DOM methods interrogate/update the DOM. Instead use a separate state. When the button is clicked transfer the text from the colorText state to the activeColor state, and use that value in the textarea's style attribute.

const { useState } = React;

function Example() {

  // Set up the states
  const [ colorText, setColorText ] = useState('');
  const [ activeColor, setActiveColor ] = useState('');
  const [ text, setText ] = useState('Example text');

  // One function to update the `colorText` state
  function handleColorText(e) {
    setColorText(e.target.value);
  }

  // One function to update the text from the
  // textarea
  function handleText(e) {
    setText(e.target.value);
  }

  // One function to take the value in the `colorText`
  // state, and apply it to the `activeColor` state
  function handleClick() {
    setActiveColor(colorText);
    setColorText('');
  }

  // The textarea now has a style attribute. It's
  // value is the value of `activeColor`.
  return (
    <div>
      <input
        type="text"
        name="color"
        value={colorText}
        onChange={handleColorText}
      />
      <button onClick={handleClick}>
        Change color
      </button>
      <textarea
        style={{ color: activeColor }}
        name="text"
        value={text}
        onChange={handleText}
      ></textarea>
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
textarea { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

CodePudding user response:

You can easily do this with hooks but if you insist in this way there are a some issues with your code. First, you are using the setcolor function to set the color state value, but you are not using it to set the color of the text. You are using the

x.style.color = setcolor(newc)

line, which is setting the color property of the element to the return value of the setcolor function, which is undefined. You should be using the setcolor function to set the color of the text like this:

x.style.color = color

Also you are using the const keyword to define the x variable, which is a reference to the element with the ID mybox. x variable cannot be reassigned, but you are trying to reassign it in the else block of your newColor function. Instead, you should use the let keyword to define the x variable so that it can be reassigned.

import React, {useState} from 'react'

export default function Textform(props) {
  const newColor = () => {
    let x = document.getElementById("mybox")
    let newc = color;
    if (x.style.color === "black") {
      x.style.color = color
    } else {
      x.style.color = "black"
    }
  }

  const changeColor = (event) => {
    setcolor(event.target.value);
  }

  const onChange = (event) => {
    setText(event.target.value);
  }

  const [text, setText] = useState("");
  const [color, setcolor] = useState("")

  return (
    <>
      <div className="mb-3">
        <textarea className="form-control" value={text} onChange={onChange} placeholder="Enter text "  name="" id="mybox"  rows="8"></textarea>
      </div>

      <div className="mb-3">
        <textarea className="form-control" value={color} onChange={changeColor} placeholder="Enter your color choice" name="" id="mybox"  rows="3"></textarea>
      </div>

      <button className="btn btn-primary mx-1" onClick={newColor}>Change Color</button>
    </>
  )
}

I removed the const keyword before the x variable in the newColor function and replaced it with the let keyword. This allows the x variable to be reassigned in the else block.

CodePudding user response:

You can make use of style tag and color property to style and a state to check if button is clicked

sample e.g.

const {useState} = React;


function App() {
  const [text, setText] = useState('');
  const [color, setcolor] = useState('');
  const [clicked, setClicked] = useState(false);
  //this is function
  const newColor = () => {
    setClicked(!clicked);
  };

  const changeColor = (event) => {
    setcolor(event.target.value);
  };

  const onChange = (event) => {
    setText(event.target.value);
  };

  return (
    <React.Fragment>
      //text area input
      <div className="mb-3">
        <textarea
          className="form-control"
          value={text}
          onChange={onChange}
          placeholder="Enter text "
          name=""
          id="mybox"
          style={{ color: clicked ? color : 'black' }}
          rows={8}
        ></textarea>
      </div>
      //our color choice input
      <div className="mb-3">
        <textarea
          className="form-control"
          value={color}
          onChange={changeColor}
          placeholder="Enter your color choice"
          name=""
          id="mybox"
          rows={3}
        ></textarea>
      </div>
      //this is my button
      <button className="btn btn-primary mx-1" onClick={newColor}>
        {' '}
        {clicked ? `Change color to black` : `Change Color to ${color}`}
      </button>
    </React.Fragment>
  );
}

ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App/>
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related