How can I format embeded tweets using ReactJs? - reactjs

I'm receiving a document from the server that receives an embeded tweet and injecting it this way:
renderDetails() {
return (
<div className="new-content">
<h1 className="title-new">{this.state.new.title}</h1>
<div className="body-new"
dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(this.state.new.content)}}
></div>
</div>
);
}
The content has this form:
<div class="new-content">
.
.
.
<blockquote>America(#VOANoticias) 27 de marzo de 2019</blockquote>
.
.
.
How can I process this data to show the blockquote formatted as a tweet?

You can pick the tweet-id from the anchor tag and use it to create the tweet programmatically.
const twitterItems = Array.from(document.querySelectorAll("a[href^='https://twitter.com']"));
twitterItems.forEach((item) => {
const extractedUrlStr = item.href;
const url = new URL(extractedUrlStr);
const tweetID = url.pathname.split("/")[3];
const parentQuote = item.parentNode;
parentQuote.innerHTML = "";
twttr.widgets.createTweet(tweetID, parentQuote);
});
For React, you would probably insert this code in componentDidMount
PS: If the blockquote is of correct defined format, just including the script in the document will format the tweet for you.
Codepen Demo

Related

How to make the link is clickable in textarea in ReactJS?

I have a page named Community where user can comment on another post
I have a problem when user comments the link but it's not displayed true
When user comments, the link is not displayed true
The function I used to convert the text to link
const convertToLink = (text) => {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var text1 = text.replace(exp, "<a href='$1'>$1</a>");
var exp2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
return text1.replace(exp2, '$1$2');
}
You cannot render HTML inside of textarea. Use <p> instead
<p dangerouslySetInnerHTML={{ __html: convertToLink(text) }}></p>

React If / else for picture src

I want the image src for to change based on the value of the "p" element. I have imported all of my images like this:
import food from '../../images/food.png'
I've tried to use if/else statements and wrapping them in a function, then mounting them with componentDidMount when the page loads up, but that doesn't work for me. Then I tried :
images = () => {
const image = document.querySelectorAll('img');
let src = image.attr('src');
if (src.valueOf() === 'Food') image.src = {food};
// Changed src.val() because that didn't work //
}
componentDidMount() {
this.images()
)}
And this does nothing for me either. Any suggestions?
MAIN BODY OF CODE:
(top of code not show)
return (
<GuideDiv>
<div className='top'>
<h1>Guides</h1>
<NewGuide to='/GuideForm'>
<h2> Add <img src={travel} alt='ravel'/> Guide </h2>
</NewGuide>
</div>
{guided.map(guide =>
<GuidePost key={guide.id}>
<div>
<UserIcon>
<img id='guide' alt='type' src={guide.guide_type}/>
</UserIcon>
<label className='under'>Guide Type</label>
<br/>
<p>{guide.guide_type}</p>
<br/>
(rest of code not shown)
Why don't you try an mapping. Something like this if its predefined set
import food from '../../images/food.png'
import car from '../../images/car.png'
let mapping = {
FOOD: food,
CAR: car
}
const images = () => {
const image = document.querySelectorAll('img');
let srcVal = image.attr('src')?.valueOf;
image.src = mapping[srcVal];
//....rest of your code
}
Check this one and let me know whether it helped you
THANK YOU!!!
With a little modification, I did the suggested object map and then:
let imgURL = {
Food: food,
Stay: stay,
Sites: sites,
Tips: tips
}
<img id='guide' alt='user' src={imgURL[guide.guide_type]}/>

Troubles with displaying cards components from function [React-Bootstrap]

I m running into some trouble trying to render bootstrap elements with ReactJS script.
To give you my user case, I got to display cards depending on some list of data created from DB. However when I loop to create my 'card's to show in a "card-desk", I observe on my browser the "card-deck" is correctly generated by react while cards elements in the loop do not to seemed generated by react in the rendered page.
So far I tried with lists of data to avoid mixing problem with DB
function DisplayUnes(){
var i = 0
const nbrArticle = 3
const items = []
const idUnes =
[
1,
2,
3
]
const titleUnes =
[
]
const dateUnes =
[
]
const bodyUnes =
[
]
//string href to github storage
const imgUnes =
[
]
for(i = 0; i<nbrArticle; i++) {
items.push(
<div className="card" key={idUnes}>
<div className="card-body">
<h5 className="card-title">{titleUnes[i]}</h5>
<p className="card-text">{bodyUnes[i]}</p>
<a>{dateUnes[i]}</a>
Go somewhere
</div>
</div>
)
}
return (items)
}
... later in the code I use the tag:
<main>
<h1>A la une</h1>
<div className="card-columns">
<DisplayUnes />
</div>
</main>
I have tried other approach like calling the function, storing the generated html and displaying it in the "card-columns" block. It seems the problem comes from the loop.. When I inspect rendered code on a browser, jsx id are not generated for elements in
Would you have any idea on how to fix this problem?
I verified multiple times all necessary dependencies are installed (using nextjs, react-bootstrap) but if someone is able to provide me a recap of them, it might still be useful.
Thx in advance for your time,
Have a nice day,
Benjamin
use this
let i = 0 instead of this var i=0;
and
for (const [index, value] of idUnes.entries()) {
items.push(
<div className="card" key={index}>
<div className="card-body">
<h5 className="card-title">{titleUnes[index]}</h5>
<p className="card-text">{bodyUnes[index]}</p>
<a>{dateUnes[index]}</a>
Go somewhere
</div>
</div>
)
}
and
change const items = [] to let items = [].

how to replace image source in react?

Could you please tell me how to replace image source in react? .I am setting a src url to my img tag.
If image is not present on server I want to replace src url to this one http://punemirror.indiatimes.com/photo/55813567.cms
if image is present on server then it fine .if not then I need to change source url to "http://punemirror.indiatimes.com/photo/55813567.cms
"
here is my code
https://codesandbox.io/s/KOrGKp3B8
I try like that
imageExists(url, callback) {
var img = new Image();
img.onload = function () {
callback(true);
};
img.onerror = function () {
callback(false);
};
img.src = url;
}
renderList() {
const lis = this.items.map((item, key) => {
var src = "http://mumbaimirror.indiatimes.com/photo/" + item.id + ".cms";
const alt = "http://punemirror.indiatimes.com/photo/55813567.cms";
return (
<li key={key}>
<a><img src={src}/><span>{item.hl}</span></a>
</li>
)
})
return (
<ul>
{lis}
</ul>
)
}
render() {
return (
<div className="list">
{this.renderList()}
</div>
)
}
}
Check if your image exists, use this method and then in your component class :
componentWillMount() {
var url = "http://mumbaimirror.indiatimes.com/photo/" + item.id + ".cms";
const alt = "http://punemirror.indiatimes.com/photo/55813567.cms";
var src = this.imageExists(url) ? url : alt;
this.setState({ src });
}
// added from the mentioned post
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
render() {
var src = this.state.src;
...
}
You can use object for this.
<object data={src} type="image/png">
<img src="http://punemirror.indiatimes.com/photo/55813567.cms" />
</object>
On component render, you need to check server-side for all present files, and return an array of all file ids you got on the server.
When you get that array of existing files, let's call it allFileIds, you just need to do :
<li key={key}>
<a><img src={allFileIds.indexOf(item.id) !== -1 ? src : alt}/><span>{item.hl}</span></a>
</li>
This will check if the required id was found on the server (it checks if the item.id value exists in the array of file ids that your server returned), and if not, render the alt property instead of the src. I hope that was clear!
First put your image collection in state instead of field.
I assume each image in your images collection contains at least one field: url. You can check your images (this.items) for existence in componentDidMount/componentWillReceiveProps. Note that your imageExists method is async - therefore you cant use it during rendering. Based on the check you can set img.src to be either undefined/null or valid URL.
Then in render check image.url and if it is missing - use default one.

WP Rest API Get Featured Image

I am building a relatively simply blog page that uses the WP Rest Api and AngularJs to show the data on the front-end.
On my home page I want to return the title, followed by the featured image, followed by the excerpt. I have pulled the title and excerpt in fine it seems that in the JSON the featured image is a media Id. What is the best way to pull this data in on the fly?
I have seen various things around the internet that use PHP functions but I think the best way to do it is within a angular controller, just looking for some advice on exactly what the controller would be
List View HTML
<ng-include src=" dir + '/form.html?v=2' "></ng-include>
<div class="row">
<div class="col-sm-8 col-lg-10 col-lg-push-1 post">
<div class="row-fluid">
<div class="col-sm-12">
<article ng-repeat="post in posts" class="projects">
<a class="title" href="#/post/{{post.slug}}"><h2>{{post.title.rendered}}</h2></a>
<p ng-bind-html="post.excerpt.rendered | to_trusted"></p>
</article>
</div>
</div>
</div>
</div>
Controller
.controller('listPage',['$scope','Posts', function($scope,Posts){
$scope.refreshPosts = function(){
Posts.query(function(res){
$scope.posts = res;
});
};
$scope.refreshPosts();
// CLEARFORMFUNCTION
$scope.clear = function(){
$scope.$root.openPost = false;
jQuery('#save').modal('hide');
};
// SAVEMODALOPEN/COSE
$scope.openSaveModal = function(){
jQuery('#save').modal('show');
}
$scope.closeSaveModal = function(){
jQuery('#save').modal('hide');
}
// DATEFUNCTION
$scope.datify = function(date){
$scope.date = newDate(date);
return $scope.date.getDate()+'/'+$scope.date.getMonth()+'/'+$scope.date.getYear();
};
}])
You could also modify the JSON response with PHP. This returns just what I need and is very fast (Using _embed is very slow in my experience)
I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme's function.php file.
php
add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field( 'post',
'featured_image_src', //NAME OF THE NEW FIELD TO BE ADDED - you can call this anything
array(
'get_callback' => 'get_image_src',
'update_callback' => null,
'schema' => null,
)
);
}
function get_image_src( $object, $field_name, $request ) {
$size = 'thumbnail'; // Change this to the size you want | 'medium' / 'large'
$feat_img_array = wp_get_attachment_image_src($object['featured_media'], $size, true);
return $feat_img_array[0];
}
Now in your JSON response you should see a new field called "featured_image_src": containing a url to the thumbnail.
Read more about modifying responses here:
http://v2.wp-api.org/extending/modifying/
And here's more information on the wp_get_attachment_image_src() function
https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/
**Note: Don't forget <?php ?> tags if this is a new php file!
Turns out, in my case, there is a new plugin available that solves this without having to make a secondary request. See my recent Q:
WP Rest API + AngularJS : How to grab Featured Image for display on page?
If you send the ?_embed param to the query, it will return more information in the response, like images, categories, and author data.
const result = await axios.get(`/wp-json/wp/v2/my-post-type?_embed`);
// Featured Image
result.data._embedded['wp:featuredmedia'][0].source_url;
// Thumbnail
result.data._embedded['wp:featuredmedia'][0]['media_details']['sizes']['medium']['source_url']

Resources