I am using the twitter embedded timeline on my application to show the twitter feed of a companies twitter account.
When I get a result from an API, the state changes to the correct values, but the twitter widget does not appear to change
TwitterCard.js
import React from "react";
export class TwitterCard extends React.Component{
render() {
return (
<a className="twitter-timeline" href={this.props.href} data-height="100%">Tweets by {this.props.ticker}</a>
)
}
}
I have attached screenshots of the react plugin output for proof of state change.
The parent class is rather large, so I have posted the render method:
render() {
return (
<div>
<NavBar/>
<div className="container-fluid">
<div className="row">
<NavBarSide clickHandler={(url) => this.handleNavClick(url)}/>
<Dashboard
errorChart={this.state.errorChart}
twitter={this.state.twitter}
status={this.state.status}
/>
</div>
</div>
</div>
)
}
The parent passes these values to the Dashboard:
import React from "react";
import { Switch, Route } from 'react-router-dom';
import { Chart } from "./Chart";
import { TwitterCard } from "./TwitterCard";
export class Dashboard extends React.Component {
render() {
return (
<div className="col-md-9 ml-sm-auto col-lg-10 pt-2 px-3">
<div className="row">
<div className="col-lg-8">
<div className="row">
<div className="col-lg-6">
<div className="card border-0">
<div className="card-body">
<Chart chart={this.props.errorChart}/>
</div>
</div>
</div>
</div>
</div>
<div className="col-lg-4">
<TwitterCard href={this.props.twitter} ticker={this.props.ticker}/>
</div>
</div>
</div>
)
}
}
You can force an update to the twitter component when the ticket changes by keying it with the ticker where you render it in your dashboard component:
<TwitterCard
key={this.props.ticker}
href={this.props.twitter}
ticker={this.props.ticker}
/>
Related
I want to return a component <SaveTask/> to a div tag where <div id="saveTask">. I tried to use this.setState(), but it changes the container and displays the <SaveTask/> component. I want to keep that container and under that container, I want to append a component after clicking a button. Is there any way to add component using document.getElementById('saveTask').
import React, { Component } from 'react'
import SaveTask from './SaveTask';
export default class TaskHeader extends Component {
constructor(props) {
super(props)
this.state = {
saveTask: false,
}
this.showComp = () => {
this.setState({
saveTask: true,
})
}
}
render() {
if(this.state.saveTask) {
return (
document.getElementById('saveTask').innerHTML = <SaveTask/>
)
}
return (
<div>
<div className="container-fluid bg-white border-bottom">
<div className="row">
<div className="col-12">
<div className="tasks-upper text-muted">TASK MANAGEMENT APP</div>
<div className="tasks-lower">
<span className="text-secondary text-size">TASK</span><button className="text-primary btn-size" type="button" onClick={this.showComp}>+</button>
</div>
</div>
</div>
</div>
<div id="saveTask">
Return a component to this section when clicking the button
</div>
</div>
)
}
}
Yeah, so the beauty of react is that you don't need to and shouldn't be updating the innerhtml to update a component. You can simply use a ternary to determine what component to show later on:
import React, { Component } from 'react'
import SaveTask from './SaveTask';
export default class TaskHeader extends Component {
constructor(props) {
super(props)
this.state = {
saveTask: false,
}
this.showComp = () => {
this.setState({
saveTask: true,
})
}
}
render() {
return (
<div>
<div className="container-fluid bg-white border-bottom">
<div className="row">
<div className="col-12">
<div className="tasks-upper text-muted">TASK MANAGEMENT APP</div>
<div className="tasks-lower">
<span className="text-secondary text-size">TASK</span><button className="text-primary btn-size" type="button" onClick={this.showComp}>+</button>
</div>
</div>
</div>
</div>
{this.state.saveTask ? (
<SaveTask/>
) : (
<div id="saveTask">
Return a component to this section when clicking the button
</div>
)}
</div>
)
}
}
In this case you're saying, "if this.state.saveTask is true, then show <SaveTask /> otherwise, show the <div id="saveTask"> element. If you wanted inside that div, then you would just move the ternary inside it.
I hope following answer will help you
Achive using Functional Component
import React, { useState } from "react";
import SaveTask from "./SaveTask";
function TaskHeader() {
const [show, setShow] = useState(false);
const showComp = () => {
setShow(true);
};
return (
<div>
<div className="container-fluid bg-white border-bottom">
<div className="row">
<div className="col-12">
<div className="tasks-upper text-muted">TASK MANAGEMENT APP</div>
<div className="tasks-lower">
<span className="text-secondary text-size">TASK</span>
<button
className="text-primary btn-size"
type="button"
onClick={showComp}
>
+
</button>
</div>
</div>
</div>
</div>
<div id="saveTask">{show && <SaveTask />}</div>
</div>
);
}
export default TaskHeader;
Achive using Class Component
import React, { Component } from 'react'
import SaveTask from './SaveTask';
export default class TaskHeader extends Component {
constructor(props) {
super(props)
this.state = {
saveTask: false,
}
this.showComp = () => {
this.setState({
saveTask: true,
})
}
}
render() {
return (
<div>
<div className="container-fluid bg-white border-bottom">
<div className="row">
<div className="col-12">
<div className="tasks-upper text-muted">TASK MANAGEMENT APP</div>
<div className="tasks-lower">
<span className="text-secondary text-size">TASK</span><button className="text-primary btn-size" type="button" onClick={this.showComp}>+</button>
</div>
</div>
</div>
</div>
<div id="saveTask">`
{ this.state.saveTask && <SaveTask/> }
</div>
</div>
)
}
}
I sending image path data from parent component(TaskSubmissions.js component) to child component(Card.js component) and same image path data I want to pass child component of Card which is CardDetail.js.
Problem is data is passed from TaskSubmissions.js to Card.js but it's not getting passed from Card.js to DetailCard.js
I am using react-router-dom . To understand it better below I am sharing all three components code. I'll appreciate your help.
P.S I am new to react and trying to understand the flow with such experiments.
Data Flow = image URL is passing from TaskSubmission.js to -> Card.js to -> DetailCard.js
Parent Component TaskSubmissions.js
import React from "react";
import Card from "../components/Card";
const TaskSubmissions = () => {
return (
<div className="container-fluid">
<div className="row justify-content-center mt-5">
<h1 className="text-info display-4 text-center">
Review All Students Task!
</h1>
</div>
<div className="row justify-content-center">
<p className="lead text-center">Rate your students performance</p>
</div>
<div className="row justify-content-center mt-5">
<div className="col-lg-3 col-md-4 col-sm-12">
<Card
name="Jane"
path="https://source.unsplash.com/aob0ukAYfuI/400x300"
/>
</div>
</div>
</div>
);
};
export default TaskSubmissions;
Child Component Card.js
import React from "react";
import { Link } from "react-router-dom";
const Card = (props) => {
return (
<div className="container-fluid">
<div className="row">
<h4 className="card-title">{props.name}</h4>
<Link
to={{
pathname: "/detail",
state: { imgpath: props.path, name: props.name },
}}
className="d-block mb-4 h-100"
>
<img
className="img-fluid img-thumbnail"
src={props.path}
alt="image"
/>
</Link>
</div>
</div>
);
};
export default Card;
GrandChild Component CardDetail.js
import React from "react";
import { useLocation } from "react-router";
const CardDetail = (props) => {
const data = useLocation();
return (
<div className="container-fluid">
<div className="row justify-content-center">
<div className="card mb-3">
<img src={data.imgpath} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{data.name}</h5>
<p className="card-text">Assignment 1 is completed.</p>
<p className="card-text">
<small className="text-muted">Last updated 3 mins ago</small>
</p>
</div>
</div>
</div>
</div>
);
};
export default CardDetail;
Try accessing it differently. You are currently doing const data = useLocation(); and then data.imgpath. Have you tried console.log(data)?
I would suggest the following change:
<img src={data.state.imgpath} className="card-img-top" alt="..."/>
<h5 className="card-title">{data.state.name}</h5>
Since you've stored it in
{{pathname: "/detail", state: {imgpath: props.path, name: props.name}}}
So it is held in data.state.
data Object should look something like this:
{
...
pathname: '/detail',
state: {
name: 'bar',
imgpath: 'foo'
}
}
I have one independent component 'notification' with its own CSS style. I want to show the notification component in my header component but with different styling. I imported the component in the header, but I unable to add style on it. Please help. I didn't want to change the notification component local style as it broke the notification functionality.
Code for importing notification component.
import React from 'react';
import bell from '../../../assets/icons/bell.svg';
import NotificationList from '../notification/NotificationList';
class Search extends React.Component{
constructor()
{
super()
this.state={
notificationStatus:false
}
}
render()
{
const style={
position:'absolute',
top:'70px',
left:'0px',
width:'100%',
height:'auto',
zindex:'2'
}
return(
<div className="col-md-8 col-sm-8">
<div className="row">
<div className="col-md-11 col-sm-11 search-container">
<input type="text" className="form-control" name="search" placeholder="Search" />
<i className="fa fa-search"></i>
</div>
<div className="col-md-1 col-sm-1 bell-container flex all-center relative">
<img src={bell} alt="bell icon" />
</div>
</div>
<NotificationList style={style} className="notification-component" />
</div>
)
}
}
export default Search;
Notification list component
import React from 'react';
class NotificationList extends React.Component{
constructor(props)
{
super(props)
this.state={
}
}
render()
{
const title={
marginBottom:'0px'
}
return(
<div className="col-md-10 col-md-offsest-1 default-shadow offset-md-1 bg-white pd-10-0 border-radius-10">
<div className="row">
<div className="col-md-12 flex pd-10-0 notification-main-block">
<div className="col-md-11">
<p className="paragraph" style={title}>Notification title comes here.</p>
<p className="small-paragraph" style={title}>2 min ago</p>
</div>
</div>
<div className="col-md-12 flex pd-10-0 notification-main-block">
<div className="col-md-11">
<p className="paragraph" style={title}>Notification title comes here.</p>
<p className="small-paragraph" style={title}>2 min ago</p>
</div>
</div>
<div className="col-md-12 flex pd-10-0 notification-main-block">
<div className="col-md-11">
<p className="paragraph" style={title}>Notification title comes here.</p>
<p className="small-paragraph" style={title}>2 min ago</p>
</div>
</div>
</div>
</div>
)
}
}
export default NotificationList;
I see you have included the style prop in your notification component,
<NotificationList style={style} className="notification-component" />
But you forgot to apply it again in your own export component Notification list component
(I tend to forget sometime, it happened to the best of us.)
<div style={this.props.style} className="col-md-10 col-md-offsest-1 default-shadow offset-md-1 bg-white pd-10-0 border-radius-10">
I highly recommend styled-components for dealing with this styling stuff. Check it out here
Edited:
After reading again, I see you misunderstand a little bit of the style,
you can apply style on most primitive html component, such as div, span, section and etc. But when it comes to component, the style actually will not automatically applied, it is purposely designed that way, and the style will be goes to you props. You have to apply it again.
Example:
const Parent = ()=>{
return (
<div>
<MyCustomChild style={{fontSize:10}}>Some text</MyCustomChild>
</div>
)
}
export const MyCustomChild = (/* Properties */ props)=>
{
const {style, children} = props // extract your 'applied' property
return (
<div style={style /* passing it here */}>
{children}
</div>
)
}
You have only passed style but not used in Notification component.
You can access it using props which in your case is this.props.style.
Ex.
<div style={this.props.style} className="col-md-10 col-md-offsest-1 default-shadow offset-md-1 bg-white pd-10-0 border-radius-10">
I'm using map to view all posts using axios. And I just want show when I click a specific post to see more information. I'm using react parameters. But it's not working.
Here is my one component
import React, {Component} from 'react';
import Album from './album'
import {Link, BrowserRouter as Router, Route} from 'react-router-dom'
import axios from "axios"
class ViewDataAPI extends Component{
state = {
posts: []
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/comments')
.then(response => {
this.setState({
posts: response.data
})
})
.catch(error => console.log('error'))
}
render(){
let { posts } = this.state
if(posts.length === 0){
return <h1>Loading...</h1>
}
else{
return(
<Router>
<div className="header">
<div className="container">
<div className="row">
<div className="col-lg-12 col-sm-12 col-xs-12">
<div className="text-center mb-20">
<h1>View Data From API</h1>
<p>using jsx-component, props, state, map in react </p>
</div>
</div>
</div>
<div className="row">
{
posts.map(post =>
{
return (
<Album
key={post.id}
name={post.name}
email = {post.email}
body = {post.body}
view = {post.id}
/>
)
}
)
}
</div>
{/* here is im using params, and to match by clicking specific id to show/view more information */}
<div className="row">
{posts && (
<Route path="/album/:albumId"
render = {({match}) => (
<ViewPosts {...posts.find(pv => pv.id === match.params.albumId)} />
)}
/>
)}
</div>
</div>
</div>
</Router>
)
}
}
}
export default ViewDataAPI;
// This component using for show details
const ViewPosts = ({posts}) =>{
return(
<div className="col-lg-6">
<div className="card border-dark mb-3">
<div className="card-body text-dark">
<div className="album">
<h3>{posts.name}</h3>
<h3>{posts.email}</h3>
<Link to="./">Back To Home</Link>
</div>
</div>
</div>
</div>
);
}
This is album component that has a link
import React, {Component} from 'react'
import {Link} from "react-router-dom"
class Album extends Component{
render(){
return(
<div className="col-lg-6">
<div className="card border-dark mb-3">
<div className="card-body text-dark">
<div className="album">
<h3>{this.props.name}</h3>
<p>{this.props.email}</p>
<p>{this.props.body}</p>
<Link to={`/album/${this.props.view}`}>View</Link>
</div>
</div>
</div>
</div>
);
}
}
export default Album;
https://react-pin.netlify.com/
Please follow the above link to what I'm trying to do. Please first go to one "View Data From API"
My github link https://github.com/sultan0/reactpin
The route param is a string. There is no implicit type conversion
with === Operator. Therefore you have to do it explicitly. Pls. see
Comparison operators for a further explanation.
The spread ... Operator is misplaced here.
The solution is:
<ViewPosts posts={posts.find(pv => pv.id === parseInt(match.params.albumId))} />
Update
You would like to use the Switch component from react router:
Switch is unique in that it renders a route exclusively. In contrast, every Route that matches the location renders inclusively.
Pls refer to react router documentation.
I created a pull request as an example. Hope it helps.
I've got a problem with react and react-router.
When I click on a link (in my example contact in Footer.js), the url changes, but the desired component Location is not shown. When I refresh the site then, the correct component is displayed.
App.js:
import React, { Component } from 'react';
import { BrowserRouter as Router, HashRouter, Route, Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.css';
import Footer from './Footer.js';
import Navigation from './Navigation.js';
import Background from './Background.js';
import Home from './Home.js';
import Products from './Products.js';
import Industries from './Industries.js';
import Partner from './Partner.js';
import Location from './Location.js';
import MeetUs from './MeetUs.js';
import ScrollUp from './ScrollUp.js';
import Divider from './Divider.js';
import Country from './Country.js';
import Language from './Language.js';
import Waypoint from 'react-waypoint';
import $ from "jquery";
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentLanguage: 'en',
currentBU: '',
currentIndustry: '',
showMainProductGroups: false,
currentCountry: 'group',
countryObject: Country['group'],
contacts: [],
mainProductGroups: [],
};
}
handleCountryChange() {
//...
}
handleLanguageChange() {
//...
}
handleBUChange() {
//...
}
render() {
const routes = [
{
path: '/',
exact: true,
components: () =>
<div>
<Home key="home" currentLanguage={this.state.currentLanguage} />
</div>,
},
{
path: '/contact',
exact: true,
components: () => <Location key="locations" currentLanguage={this.state.currentLanguage} country={this.state.countryObject} contacts= {this.state.contacts} onCountryChange={this.handleCountryChange.bind(this)} />
},
]
return (
<HashRouter>
<div>
<Background />
<div id="wrap">
<div id="main" className="container clear-top marginBottom50px">
<div id="content">
<Navigation key="navBar" currentLanguage={this.state.currentLanguage} onLanguageChange={this.handleLanguageChange.bind(this)} onBUChange={this.handleBUChange.bind(this)} onCountryChange={this.handleCountryChange.bind(this)} />
{
routes.map((route, index) => (
<Route key={index} path={route.path} exact={route.exact} component={route.components} />
))
}
</div>
</div>
</div>
<Footer key="footer" currentLanguage={this.state.currentLanguage} />
<ScrollUp key="scrollUp" />
</div>
</HashRouter>
);
}
}
export default App;
Home.js:
import React, { Component } from 'react';
import $ from "jquery";
import { Link } from 'react-router-dom';
import {withRouter} from 'react-router';
import Language from './Language.js';
import locations from './locations.jpg';
import locationLegend from './locationLegend.jpg';
require('bootstrap')
class Home extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div className="container marginTop50px marginBottom50px area">
<div className="row">
<div className="col-12 text-center animDelay2 fadeInDown animated">
<h1>International Distribution of Specialty Chemicals</h1>
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center animDelay2 fadeInUp animated">
{Language[this.props.currentLanguage].homeStartText}
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
<img src={locations} className="img-fluid" alt="Locations" />
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
<img src={locationLegend} className="img-fluid" alt="Locations" />
</div>
</div>
</div>
);
}
}
export default withRouter(Home);
Location.js:
import React, { Component } from 'react';
import $ from "jquery";
import { Link } from 'react-router-dom';
import Language from './Language.js';
import Country from './Country.js';
import ContactPerson from './ContactPerson.js';
import locations from './locations.png';
import phone from './phoneBlack.svg';
import fax from './faxBlack.svg';
import email from './emailBlack.svg';
import {withRouter} from 'react-router';
require('bootstrap');
class Location extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('Country change:' + this.props.country.key);
$('#selectCountry').val(this.props.country.key); //name['en']
}
onCountryChange() {
let countryName = this.refs.country.value;
this.props.onCountryChange(countryName);
}
render() {
return (
<div className="container marginTop50px marginBottom50px area" id="locations">
<div className="row">
<div className="col-12 text-center">
<h2>{Language[this.props.currentLanguage].locations}</h2>
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
<div className="form-group">
<select id="selectCountry" className="form-control" ref="country" onChange={this.onCountryChange.bind(this)}>
<option defaultValue>{Language[this.props.currentLanguage].selectLocation.toUpperCase()}</option>
{
Object.keys(Country).map((countryKey) => {
const country = Country[countryKey];
return (
<option value={countryKey} key={"loc" + countryKey}>{country.name[this.props.currentLanguage].toUpperCase()}</option>
);
})
}
</select>
</div>
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
{this.props.country.name[this.props.currentLanguage].toUpperCase()}
<br />
<address>
<span dangerouslySetInnerHTML={{__html: this.props.country.address}}></span>
<br />
<br />
<img src={phone} alt="Anrufen" className="phoneMain"></img><span> </span>
<a href={this.props.country.phoneHTML}>{this.props.country.phone}</a>
<br />
<img src={fax} alt="Fax" className="phoneMain"></img><span> </span>
<a href={this.props.country.faxHTML}>{this.props.country.fax}</a>
<br />
<img src={email} alt="Email" className="emailMain"></img><span> </span>
<a href={"mailto://" + this.props.country.email}>{this.props.country.email}</a>
</address>
</div>
</div>
<div className="row marginTop25px">
<div className="col-12 text-center">
{Language[this.props.currentLanguage].vatRegistrationNumber + ": " + this.props.country.vatNo}
<br />
{Language[this.props.currentLanguage].registrationOffice + ": "}
<span dangerouslySetInnerHTML={{__html: this.props.country.registrationOffice}}></span>
</div>
</div>
<div className="row marginTop50px">
<div className="col-12 text-center">
<h3>{Language[this.props.currentLanguage].contact}</h3>
</div>
</div>
<div className="row">
{
this.props.contacts.map((contact) => {
return (
<div className="col-12 col-sm-12 col-md-12 col-lg-6 text-center">
<ContactPerson contact={contact} key={"contact" + contact.id} />
</div>
);
})
}
</div>
</div>
);
}
}
export default withRouter(Location);
Footer.js:
import React, { Component } from 'react';
import $ from "jquery";
import { Link } from 'react-router-dom';
import {withRouter} from 'react-router';
import Language from './Language.js';
import phone from './phoneWhite.svg';
import fax from './faxWhite.svg';
require('bootstrap');
class Footer extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<footer className="footer">
<div className="container-fluid borderTop1px footerLayout">
<div className="row">
<div className="col-3">
<address>
<small>
Some text
</small>
</address>
</div>
<div className="col-6 text-center">
<div className="row">
<div className="col-12 col-sm-12 col-md-12 col-lg-3 text-center">
<small>{Language[this.props.currentLanguage].download}</small>
</div>
<div className="col-12 col-sm-12 col-md-12 col-lg-3 text-center">
<Link to="/imprint" className="nav-link footerLink"><small>{Language[this.props.currentLanguage].imprint}</small></Link>
</div>
<div className="col-12 col-sm-12 col-md-12 col-lg-3 text-center">
<Link to="/contact" className="nav-link footerLink"><small>{Language[this.props.currentLanguage].contact}</small></Link>
</div>
<div className="col-12 col-sm-12 col-md-12 col-lg-3 text-center">
<Link to="/termsAndConditions" className="nav-link footerLink"><small>{Language[this.props.currentLanguage].termsAndConditions}</small></Link>
</div>
</div>
</div>
<div className="col-3">
<ul className="list-inline">
<li>
<img src={phone} alt="Anrufen" className="phone"></img> <small><a className="footerLink" href="tel:+49">+49</a></small>
</li>
<li>
<img src={fax} alt="Fax" className="phone"></img> <small><a className="footerLink" href="tel:+49">+49</a></small>
</li>
</ul>
</div>
</div>
</div>
</footer>
);
}
}
export default withRouter(Footer);
What I'm doing wrong? Why it is not working, when I click on a link?
Got it working now.
I needed to change <HashRouter> to <Router>. Then it works fine.
UPDATE:
This solution solves the problem, but then there is a different problem: When I have navigated and refresh the page, then an error (404) is thrown, because there is of course no such a page on the server.
I need to get the HashRouter work.
When you declare your routes in App.js, you should pass the props to the component:
components: props => <Location {...props} <insert other props> />
You should stick to the <Router> solution as having unnecessary hash in the url is ugly.
When I have navigated and refresh the page, then an error (404) is thrown, because there is of course no such a page on the server.
To resolve this, you need to set up a redirect to redirect all requests to the base url for the React app to handle (the url displayed will be preserved).
On Netlify, you can create a _redirects file in your public folder with the content:
/* /index.html 200
On AWS S3, the redirect rules can be set in S3 or CloudFront, see the answers here.
For Google Cloud bucket, see this.
For Github pages, see this.
In your Route component you use component prop to pass the Location component (instead of render or children props available on Route) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop.However in your case it seems you are using it for no reason so you should just pass the component and not an inline function that returns it like so :
const routes = [
{
path: '/',
exact: true,
components: <Home key="home" currentLanguage={this.state.currentLanguage}/>
},
{
path: '/contact',
exact: true,
components: <Location key="locations" currentLanguage={this.state.currentLanguage} country={this.state.countryObject} contacts= {this.state.contacts} onCountryChange={this.handleCountryChange.bind(this)} />
},
]
Make your routes use Component as below
import {IndexRoute, Route} from 'react-router';
<Route component={App}>
<Route path='/locations' component={LocationComponent}/>
</Route>
This is what I am doing in my current project without using HashRouter.
Currently, When you do
<Route key={index} path={route.path} exact={route.exact} component={route.components} />
I don't think {route.components} treats it as a component.
Could be a problem with withRouter().
Have you seen this?
https://github.com/ReactTraining/react-router/issues/5037