nyphur
nyphur

Reputation: 2866

How do I add an anchor tag to a string prop?

I have a reusable input/checkbox component that takes in a label prop:

<Checkbox
  label="I have read and understood the Terms of Service and consent to the Privacy Policy"
/>

and my checkbox's render:

<label>
    <input
        type='checkbox'
        disabled={this.props.disabled}
        onChange={this.handleChange}
        checked={this.props.value}
        placeholder={this.props.placeholder}
    />
        {this.label}
</label>

however I want the label to accept something like

<Checkbox
  label="I have read and understood the <a href="http://....">Terms of Service</a> and consent to the <a href="http://....">Privacy Policy</a>"
/>

and have the words Terms of Service and Privacy Policy as links. However this doesn't work.

Do I have to use something like dangerouslySetInnerHtml to achieve something like this? From wha tI understand using innerHTML is a risk, is it not?

What would be the best way to modify my component to be able to add links like this?

Upvotes: 3

Views: 1652

Answers (1)

skovy
skovy

Reputation: 5650

You can pass in JSX for the label prop instead of a string, for example:

<Checkbox
  label={
    <>
      I have read and understood the <a href="http://....">Terms of Service</a>{" "}
      and consent to the <a href="http://....">Privacy Policy</a>
    </>
  }
/>;

Here is a full example:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Checkbox = props => {
  return (
    <label>
      <input
        type="checkbox"
        disabled={props.disabled}
        onChange={props.handleChange}
        checked={props.value}
        placeholder={props.placeholder}
      />
      {props.label}
    </label>
  );
};

function App() {
  return (
    <div className="App">
      <Checkbox
        label={
          <>
            I have read and understood the{" "}
            <a href="http://....">Terms of Service</a> and consent to the{" "}
            <a href="http://....">Privacy Policy</a>
          </>
        }
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You can view the full interactive example here

Upvotes: 5

Related Questions