1

I have a React app where a user can type something into textbox, click 'submit' and then the text appears somewhere.

I want to add functionality which will allow the user to format the text. Just like you can do here on SE when asking questions. For example I want the below input to be shown as bold.

<b>bold</b>

How can I achieve this? Or where to look for this kind of thing?

2 Answers 2

1

If you want to enable the same functionality you get in stack overflow, then I think the one way to achieve this would be allowing the user to input markdown and converting that to HTML. This is a library that could help with that: marked

Freecodecamp has a markdown previewer as one of their projects, so if you want to check out some examples, you could probably find hundreds of different implementations: https://www.freecodecamp.org/forum/t/build-a-markdown-previewer/198715

Sign up to request clarification or add additional context in comments.

1 Comment

Very helpful, thanks. react-markdown works perfectly for me. Do you know about any easy way to combine it with Latex?
1

Yes, this can be done using state, as well as a checkbox toggle to determine whether or not the text should be bold or not.

handleChange will update the input. handleFormatChange will update whether or not you should use bold text or not. In the render, a conditional can be implemented to determine when to render what format.

class Formatter extends React.Component {

  state = {
    format: false,
    input: ""
  }

  handleChange = () => {
    this.setState({
      input: event.target.value
    })
  }

  handleFormatChange = () => {
    this.setState({
      format: !this.state.format
    })
  }

  render() {
    var input = this.state.format 
    ? <b> {this.state.input} </b> 
    : <p> {this.state.input} </p>

    return ( 
      <div>
         Bold <input type="checkbox"
                     onChange = {
                       this.handleFormatChange
                     }
              />
              <br />
              <input value={this.state.input}
                     onChange = {this.handleChange}
              /> 
              <br/>
              {input} 
      </div>
    );
  }
}


ReactDOM.render( <
  Formatter / > ,
  document.getElementById('root')
);
p {
  margin-top: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
  <!-- This element's contents will be replaced with your component. -->
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.