How to get meta values in reactJs? - reactjs

I am working on react application.I need meta tags value(description,title,etc).I am not able to access it.I need for navigator share api.My code is:
import React, { Component } from 'react';
import { Button } from 'semantic-ui-react'
class App extends Component {
constructor(props){
super(props);
this.getOpenGraphData = this.getOpenGraphData.bind(this);
}
getOpenGraphData(property){
return document.querySelector(`meta[property="${property}"]`)
.getAttribute('content');
}
handleClick(){
navigator.share({
title: getOpenGraphData('og:title'),
text: getOpenGraphData('og:description'),
url: getOpenGraphData('og:url')
})
.then(() => {
console.log('Successfully shared');
alert("successfully shared")
})
.catch((error) => console.log('Error sharing:', error));
}
render() {
return (
<div>
<Button content='Click Here' onClick={this.handleClick.bind(this)}/>
</div>
);
}
}
export default App;
But i am not able to access meta properties.Where I am doing wrong??

I think the issue is not with selecting the meta tag, but with navigator.share() as it is an experimental feature not fully supported by all browsers, check here.
You can check if navigator is supported before calling it:
if (navigator.share) {
navigator.share({...});
}

Related

Add fade-in animation to a list element in React

I have the following code that display a table's data from Laravel using axios in React.
The data is displayed in real time. How can I add a fade-in animation each time a new element is added ? https://socket.io/ shows exactly what I want to do in the example on the right.
Note that the element in the li tag is added from an event that is fired up from a creation controller.
The component :
import React,{Component} from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import Echo from "laravel-echo";
class Patient extends React.Component {
constructor(props) {
super(props)
this.state = {
patients : [],
};
}
componentDidMount() {
axios.get('api/patients')
.then(response => {this.setState({patients: response.data})})
.catch(err => console.log(err));
window.Echo.channel('home')
.listen('NewPatient', newPatientData => {
this.setState({
patients: this.state.patients.concat(newPatientData)
})
}, e => {
console.log("Error", e)
})
}
render() {
return (
<div>
<ul> { this.state.patients.slice(0).reverse().map(patient => <li>{patient.nom}</li>)} </ul>
</div>
)
}
}
export default Patient;
You can do this pretty easily with CSS animations. I've created an example below for you and if you check out the CSS, you'll see the keyframe animation which is then used by the .fadeIn selector and that class is then applied to the <li> element.
https://codesandbox.io/s/dreamy-frog-r6sr8?file=/src/styles.css

React - what are the steps to get data from api and render it?

I am building a site just like stackoverflow.com. I want my home page to display top questions. For that, I have sample questions on the backed. Now, I want to display only the question and tags from the questions array.
The code is in the image
I have made axios connection for that:
const instance = axios.create({
baseURL: "https://2w2knta9ag.execute-api.ap-south-1.amazonaws.com/dev", });
instance.defaults.headers.post["Content-Type"] = "application/json";
To connect it, I wrote the command: instance.get("/questions)
Now, how do I display only the question and tags??
EDIT:
On using the code given bellow, my js file now becomes:
import React from 'react';
import instance from '../../api';
class QuestionList extends React {
componentDidMount() {
instance
.get("/questions")
.then((res) => {
this.setState({ data: res.data });
});
}
render () {
const { data } = this.state;
return <div>
{
data && data.map(d => {
return <div>question: {d.question}, tags: {d.tags}</div>;
})
}
</div>
}
}
export default QuestionList;
But, this is just making my site in a loading state, and it gets hanged!!
If I understood correctly, you want to get an array only with the tags and the question. if so, you can use Array.prototype.map for this
const questions = result.map(({ question, tags }) => ({ question, tags }))
First you export the axios instance so that it can be used from other components.
Now you can send the api request in componentDidMount and update your component's state with the data.
And in render function, you just get the value from state and display.
If you are new to react, learn React Hooks and know that componentDidMount method is the best place to send api requests.
For Example:
import React from 'react';
import instance from '../../api';
class QuestionList extends React.Component {
constructor() {
super();
this.state = {
data: [],
};
}
componentDidMount() {
instance.get('/questions').then((res) => {
this.setState({ data: res.data });
});
}
render() {
const { data } = this.state;
return (
<div>
{data &&
data.map((d) => {
return (
<div>
question: {d.question}, tags: {d.tags}
</div>
);
})}
</div>
);
}
}
export default QuestionList;

Using ReactJs to fetch data from an API but getting completely blank page with no errors

Guys Kindly i need your help. I am trying to fetch data from an Api and display it in the dom. I can see the data in the console but when i try to return data it shows a blank page and no errors. Below is my code.
App.js file
import React from "react";
import "./App.css";
import Movieapp from "./Movieapp";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
title: [],
date: [],
image: []
};
}
componentDidMount() {
fetch(`https://yts.mx/api/v2/list_movies.json?quality=3D`)
.then(res => res.json())
.then(data => {
console.log(data.data);
this.setState = {
title: data.data.movies[0].title,
date: data.data.movies[0].date_uploaded,
image: data.data.movies[0].background_image
};
});
}
render() {
return (
<div className="App">
<Movieapp
title={this.state.title}
date={this.state.date}
image={this.state.image}
/>
</div>
);
}
}
export default App;
Movieapp.js file
import React from "react";
const Movieapp = props => {
return (
<div>
<h1>{props.title}</h1>
<h1>{props.date}</h1>
<div>{props.image}</div>
</div>
);
};
export default Movieapp;
this.setState is a function, not a property. You have to use it properly:
this.setState({
title: data.data.movies[0].title,
date: data.data.movies[0].date_uploaded,
image: data.data.movies[0].background_image
});
Also, even though I guess you are just trying things our, there are few things to be aware of:
movies[0] can be undefined
You are getting multiple movies but showing only one. It's probably better to just save the whole data array in the state and iterate over the results in the render method

server side rendering react Issue rendering a subroute

I have a route: /events with a subroute /events/:id
I created a reducer and an action for fetching all the events and display them in the eventsPage.
This part works fine.
Now from the events page, when I click on an event I'm trying to navigate to /events/:id
In the events/:id page I created an action which is called in the componendDidMount callback then display the event from there.
It works fine when I click on a link to an event's details page from the list. Now I'm looking for the way to perform the request on the server side so when I do a full reload of the page, the selected event is still displayed.
Here is my events/:id page component
import React, { Component } from 'react';
import {connect} from 'react-redux';
import {fetchEvent} from '../actions/eventsActions'
class EventDetail extends Component {
constructor(props){
super(props);
this.state = {
event: null
}
}
componentDidMount(){
this.props.fetchEvent(this.props.match.params.slug).then(response => {
this.setState({
event: response.event
})
}).catch(error => {
console.log('error', error);
});
}
render() {
return (
<div>
{JSON.stringify(this.state)}
</div>
);
}
}
function loadData(store){
}
export default {
component: connect(null, {fetchEvent})(EventDetail),
loadData
};
my fetch_event action
import {FETCH_EVENT} from './types';
export const fetchEvent = (event_slug) => async(dispatch, getState, api) => {
const res = await api.get(`/api/events/${event_slug}`);
dispatch({
type: FETCH_EVENT,
payload: res.data
})
return res.data;
}
How can I fix this?

React componentDidMount does not show axios response

I have React component RandomQouteMachine which is supposed to get response from the provided URL and display it on the page. I don't see response displayed. The debug 'Did component mount ?' message is missing too..
import React, { Component } from 'react';
import axios from 'axios';
lass RandomQouteMachine extends Component {
constructor(props) {
super(props);
this.state = {
data: ""
};
}
componenetDidMount() {
console.log('Did component mount ?');
axios.get('https://api.icndb.com/jokes/random')
.then((res) => {
this.setState({data:res.value.joke});
})
}
render() {
return (
<div>
Here it is:
{this.state.data}
</div>
);
}
}
export default RandomQouteMachine;
Am I using componenetDidMount() correctly ? I can see only 'Here it is:' displayed on page
check your spelling.
componenetDidMount !== componentDidMount

Resources