How to click an image and reload the current page in Reactjs? - reactjs

I'm still a newbie in Reactjs and I'm trying to build a single page for my project. And I'm thinking to click the logo image and reload the page.
I have tried 2 ways, one is using <a href="javscript:location:reload: true"> in front of image element but I got this Script URL is a form of eval no-script-url in my console.
I also tried onClick eventlistener but nothing is working.
I appreciate any helps, or new way to build this?
Below is my Home.js
class Home extends React.Component {
render() {
return (
<div>
<img src={MindScribeLogo} className="HomePage" alt="logo" />
<div>
<img src={MindScribeZebra} className="HomePage" alt="zebra" />
</div>
</div>
);
}
}
export default Home;
Below is my App.js
class App extends Component {
render() {
return (
<div className="App">
<Home/>
);
}
}

Hmm you can try a basic onClick function. hrefs are not supposed to contain scripts.
<img onClick={() => this.reloadPage()}/>
reloadPage () {
window.location.reload()
}

Related

React tailwind, cannot pass tailwind css from parent to child

I am running into a simple issue that doesn't seem to have an answer on quick google search or Tailwind doc.
I am a Vuejs user but I have started learning React. I have opted to use TailwindCSS for testing my React application but I noticed there is some differences of Tailwind usage between Vuejs and React.
In Vue, I can control a child component via the parent component like so:
Parent component:
<template>
<div class="w-screen">
<ChildComponent class="w-1/2 mx-auto" />
</div>
</template>
With the child being able to centre on screen through the above parent component as should in the ChildComponent's class.
However, when I tried to do the same in React like so:
Parent component:
import Homepage from './views/Homepage';
function App() {
return (
<div className='bg-black w-screen'>
<Homepage className="w-1/2 mx-auto"/>
</div>
);
}
export default App;
Nothin happens when I placed the CSS at the Homepage child component from the parent.
I am sure there is a simple answer but I wasn't about to search the doc or use any keywords to find this problem. Anyone got a hint or confirm this is intended in React or have I done something wrong with the installation?
This is less of a Tailwind question and more of a React question. You cannot use className on the Homepage component without passing it as a prop. In your case, Homepage is not expecting any className. So while making your Homepage component you have to provide a prop called 'className' then it will work fine.
Or if you simply use a div in place of Homepage it will work normally. Have a look at this codesandbox link
You need to consider that <Homepage/> is a React component and cannot accept HTMLAttrs just like that.
this example might clear it:
const app = () => {
<div className="bg-black">
<Homepage className="bg-red" />
</div>
}
const homePage = (props) => {
<div className={props.className}>
<h1 className="bg-red">hi</h1>
</div>
}
the className that you pass to <Homepage/> is actually a props rather than Html attribure.
In Vue it's fairly straightforward but in react you need to be explicit and use className in your component
// Creating component
const Button = ({ className, children }) => {
return <button className={`${className} bg-red-500`}>{children}</button>
}
export default Button
// Using component
<Button className="text-white">MyButton</Button>
import Homepage from './views/Homepage';
function App() {
return (
<div className='bg-black w-screen'>
<Homepage className="w-1/2 mx-auto"/>
</div>
);
}
export default App;
views/Homepage
you have to receive props that are going to be passed as className
const homePage = ({className}) => {
<div className={className}>
<h1 className="bg-red">hi</h1>
</div>
}
export default homePage
then export your component

How to create a second component on react using the data from the API and create a dynamic URL

I have a component showing the list of blogpost and I create a URL for every post coming from the title, into a string and then split and joint, but I need to create a second component that render the page of the blogpost itself,
my question is, is there any way to pass the state or props from the already created list component into the blogpost component and be access only by that rout URL?
this is the blogdata component that i wanted to use to transfer the state to the other components but only one is working, fetching the data from the API into this.state.blogpost
class BlogData extends Component{
state = {
blogData: []
}
componentDidMount() {
axios.get(`data.json`)
.then(res => {
const blogData = [res.data.blogPosts] ;
this.setState({blogData});
})
};
render(){
const blogData = this.state.blogData.map((value) =>
value.map((val, idx) =>
<BlogBlock
link={val.title.toString().toLowerCase().split(" ").join("-")}
title={val.title}
subtitle={val.subtitle}
thumb={val.thumb}
idx={idx}
/>
)
)
return(
<section id="blog" className="blogList">
<h2>From the Blog</h2>
<div className="blogPosts">
{blogData}
</div>
</section>
)
}
}
const BlogBlock = (props) => {
return (
<div className={`blog-post post-${props.idx}`}>
<Link to={props.link}>
<Img loader={<span className="loading-img">loading....</span>} src={`http://brittdepetter.com/images/${props.thumb}`} alt={props.title} />
<h3>{props.title}<span><br />{props.subtitle}</span></h3>
</Link>
</div>
)
}
and the component that im trying to create but not working is this one, but no lock of making the route works :(
const BlogPost = (props) => {
return (
<div>
<Router path={props.link} />
<Title title={props.title } />
<div className="textBox boxImg">
<div className="story-img-box">
<Img src={props.imgsrc } />
</div>
<div>
<Paragraph body={props.body} />
</div>
</div>
</div>
)
}
There is way to pass a extra parameter on Link. For that you should pass to attribute as object instead of string.
change your Link
<Link to={props.link}>
to
<Link to={{pathname:props.link, blog:props}}>
In your BlogPost component, access using following code
this.props.location.blog
PS. refreshing browser while you are on BlogPost component will require to re-fetch a blog again.

Load a Popup Component

I am trying to display a detail component in a popup window. My App.js component contains a List component with list of Item component. When click Item component, I want to show a Detail popup. The togglePopup() function is passed from parent List component to child Item then to Detail. Right now, the popup does not show up. Below is my code:
App.js
class App extends Component {
state={ showPopup: false,
selectedItem:'',
Items:[]};
togglePopup=()=> {
this.setState({
showPopup: !this.state.showPopup
});
}
onItemseSelect=(item)=>{
this.setState({selectedItem:item});
};
render(){
const Items=['aa','bb','cc'];
return(
<List
Items={this.state.Items}
onItemSelect={this.onItemSelect}
onClick={this.togglePopup}
/>
{this.state.showPopup ?
<Detail
item={this.state.selectedItem}
closePopup={this.togglePopup.bind(this)}
/>
: null
}
);
}
}
List.js
import React from 'react';
import Item from './Item';
const List=({Items,onItemSelect,onClick})=>{
const renderedList= Items.map(item=>{
return (
<Item key={item.ID} item={item} onItemSelect={onItemSelect} onClick={onClick} />
);
})
return <div>
{renderedList}</div>
}
export default List;
Item.js
import React from 'react';
const Item=({item, onItemSelect,onClick})=>{
return <div onClick={()=>onItemSelect(item)} >
<div class="content">
<div class="header">
{/*display contents*/}
<button onClick={onClick}>View More</button>
</div>
</div>
};
export default Item;
Detail.js
import React from 'react';
const Detail=({item,closePopup})=>{
if (!item){
return <div>loading</div>
}
return (
<div>
<p>
{/*contents here*/}
</p>
<button onClick={()=>closePopup}>close me</button>
</div>);
};
export default Detail;
You have not set state to show popup, do this
onItemseSelect=(item)=>{
this.setState({selectedItem:item, showPopup: true}); //make showPopup to true so that popup get displayed
};
Note: As you are using arrow function, no need to bind this here,
closePopup={this.togglePopup.bind(this)}
You can change this to,
closePopup={this.togglePopup}
Another thing is, don't do this,
<div onClick={()=>onItemSelect(item) togglePopup={togglePopup}} > //This is wrong way to call two functions
<div onClick={()=> {onItemSelect(item); togglePopup;}} > //This is right way to call two functions
If you call togglePopup on every item click, then every time selectedItem:'' will set item to blank and you won't be able to see anything on page
Side note: Detail is a component and not a popup. This component will get display on App component after this.state.showPopup get true value. To show it as popup you must use Modal.

React - use button for redirect link

I'm new to React so sorry if this is too basic.
I am trying to add a button in my app to redirect it to Spotify.
This is how I'm trying to do it, so far.
class Spotify extends Component {
constructor () {
super()
this.handleClick = this.handleClick.bind(this)
}
handleClick () {
console.log('Success!')
}
render () {
return (
<div className='button__container'>
<button className='button' onClick={this.handleClick}>
Link your Spotify account
</button>
</div>
)
}
}
export default Spotify;
Now, what is the best way of linking the above button to:
I think you're looking for something like this:
class Spotify extends Component {
render () {
return (
<div className='button__container'>
<a className='button' role="button" href="http://someurl.com">
Link your Spotify account
</a>
</div>
)
}
}
export default Spotify;
If your component doesn't require state, consider refactoring the above code into a stateless component like so:
export const Spotify = () => (
<div className='button__container'>
<a className='button' role="button" href="http://someurl.com">
Link your Spotify account
</a>
</div>
);
If you are just trying to display a link, an anchor tag will work just fine. You can add target="_blank" to your anchor tag to have it open in a new tab.

React : Script 'Failed to compile' using componentDidMount()

Setup
I've loaded the Vanilla JS library lightgallery.js through NPM and importing it as normal.
Issue
I'm initializing this library through componentDidMount(), but it's failing to compile because 'lightGallery' is not defined. see sample below
I verified the library is importing by removing componentDidMount() and initializing it through the Chrome Console. When I do this, it works as intended.
I'm not clear on why it's resulting in 'lightGallery' is not defined when the import clearly works when i don't initialize it with componentDidMount(). I'm guessing it's either an issue with the elements not being present in the DOM at load or it's an issue with the way my import is setup.
Any help would be appreciated.
Current Page
This is a stripped down version of my setup with the gallery elements hardcoded for easy explanation.
import React, { Component } from 'react';
import 'lightgallery.js';
class Gallery extends Component {
componentDidMount() {
lightGallery(document.getElementById('lightgallery'));
}
render() {
return (
<>
<section>
<h1>Gallery</h1>
</section>
<section>
<div id="lightgallery">
<a href="img/img1.jpg">
<img src="img/thumb1.jpg" />
</a>
<a href="img/img2.jpg">
<img src="img/thumb2.jpg" />
</a>
<a href="img/img3.jpg">
<img src="img/thumb3.jpg" />
</a>
</div>
</section>
</>
);
}
}
export default Gallery;

Resources