How to create a button in React which changes the font-weight of the new input to bold?

Viewed 135

import React, { useState } from "react";

const App = () => {
  const [isBold, setBold] = useState(false);

  const handleClick = () => {
    setBold((prevValue) => {
      return !prevValue;
    });
  };

  return (
    <div>
      <input
        style={{ fontWeight: isBold ? "bold" : "normal" }}
        name="content"
      />
      <button onClick={handleClick}>Bold</button>
    </div>
  );
};
export default App;

This changes the style of the whole content of input but rather I want to just Change the font-weight of the new input. Can anyone give me full code for this or a brief explanation on how to create such a button?

1 Answers

Try using props in your code. I'm attaching a sample code which you can try experimenting on. Basically, what I have done is, I used 2 styles that is font weight and font style with the style attribute here . Refer to the documentation for a better understanding of Props. Hope this helps!

import React, { useState } from "react";

function Avatar(props) {
  return (
  <img className="avatar" src={props.user.avatar} alt={props.user.name} 
 />
 );
 }

 function UserInfo(props) {
 return (
 <div className="UserInfo">
  <Avatar user={props.user} />
  <div
    className="UserInfo-name"
    style={{ fontWeight: props.fontWeight, fontStyle: props.fontStyle }}
  >
    {props.user.name}
  </div>
  </div>
  );
   }

 export default function Comment(props) {
 const [textBold, setTextBold] = useState("none");
 const [textItalic, setTextItalic] = useState("none");
 const textChangeBold = () => {
 setTextBold("bold", "normal");
  };
 const textChangeItalic = () => {
 setTextItalic("italic");
  };

  return (
  <>
  <div className="card">
    <div className="card-body">
      <h5 className="card-title">
        <div className="Comment">
          <UserInfo user={props.author} />
        </div>
      </h5>
     
      <div className="Comment-text">{props.text}</div>
      <a
        href="https://reactjs.org/docs/components-and-props.html"
        className="card-link"
      >
        Reference
      </a>
    </div>
  </div>

  <div className="card">
    <div className="card-body">
      <h5 className="card-title">
        <div className="Comment">
          <UserInfo
            user={props.author}
            fontWeight={textBold}
            fontStyle={textItalic}
          />
        </div>
      </h5>
      {/* <h6 className="card-subtitle mb-2 text-muted">Card subtitle</h6> */}
      <div className="Comment-text">{props.text}</div>
      <button
        id="boldBtn"
        value={textBold}
        className="btn btn-primary"
        onClick={textChangeBold}
      >
        BOLD
      </button>
      <button
        id="italicBtn"
        value={textItalic}
        className="btn btn-primary"
        onClick={textChangeItalic}
      >
        ITALIC
      </button>
    </div>
  </div>

  </>
  );
  }
Related