Random quote generator: Sharing the quote to twitter

#react
Hello everyone…
I’m currently stuck with trying to share my quote to twitter. when I click the share button it loads to new page and displays:

Not Found

The link is prefixed with some text which I didn’t add and don’t understand:

https://cdpn.io/cpe/boomboom/
then my quote
twitter.com/intent/tweet?text=The%20best%20revenge%20is%20massive%20success.-%20Frank%20Sinatra
What I have tried
I removed the >https://cdpn.io/cpe/boomboom/ it solved the problem.
Question
How do I prevent the link from carrying the text that ends up breaking it ?, So it load directly from the page
My code

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      quotesArray: quotes,
      colorArray: color,
      index: 0,
      currQuote: "",
      currAuthor: ""
    } 
    this.nextQuote = this.nextQuote.bind(this)
    this.tweetQuote = this.tweetQuote.bind(this)
} 
  
  nextQuote() {
    this.setState(
      (state)=> {
         return {
        index: Math.floor(Math.random() * (state.quotesArray.length - 0) + 0),
        currQuote: state.quotesArray[state.index].text,
        currAuthor: state.quotesArray[state.index].author 
     } 
   }  
 )
}
  tweetQuote() {
       document.getElementById("tweet-quote").setAttribute("href", `twitter.com/intent/tweet?text=${this.state.currQuote}${this.state.currAuthor}`) 
  }
    render() {
  return (
    <div  id = "quote-box">
        <QuoteSection quote = {this.state.currQuote} author = {this.state.currAuthor} />
      hello
      <a  target = "_blank" id = "tweet-quote">
        <FaTwitter  onClick = {this.tweetQuote} />
      </a>
      <button id = "new-quote" >
        New quote
      </button>
    </div>
    ) 
  }
}
function QuoteSection(props) {
  return (
    <div id = "text">
      <h2><FaQuoteLeft />
       {props.quote}
      </h2>
      <h3 id = "author">{props.author}</h3>
    </div>
  )
}

Please post a link to your Codepen.


You don’t need an onClick handler, or setAttribute. Just set the href to the URL plus the state variables in the JSX.

You can’t use target="_blank" on Codepen with the Twitter intent as the pen runs inside an iframe and that isn’t allowed (it will be blocked).

Add https:// in front of the URL.

As said you have to remove target="_blank" for the link to work with Codepen. If you use the Debug view you can test that it works, but in any other view the pen will be inside an iframe and the link will be blocked.

1 Like

It works !!! :slightly_smiling_face: Thank you @lasjorg

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.