React - use button for redirect link - reactjs

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.

Related

How can I link to another website in React?

I have these div cards with some information, and I would like to insert a link inside them, that redirects to another site. It didn't work with <a></a>. can anybody help me?
Thanks!
import React from "react";
function Card(props) {
return (
<div className="card">
<img className="img-logo" src={props.img} alt="image_logo" />
<h3 className="name"> {props.name}</h3>
<p className="paragraph"> {props.description}</p>
<a href={props.link}>Page</a>
</div>
);
}
export default Card;
You can use the <Link> component from react router.
If you are opening the url in new tab, make sure to use noopener and noreferrer so that the browser does not attach the current website's window variable to the newly opened url in the new tab, which can be a security loophole.
import { Link } from 'react-router-dom';
export const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer');
if (newWindow) newWindow.opener = null;
};
function Card(props) {
return (
<div className="card">
<img className="img-logo" src={props.img} alt="image_logo" />
<h3 className="name"> {props.name}</h3>
<p className="paragraph"> {props.description}</p>
<Link href="#" onClick = {() => openInNewTab(props.link)}>Page</Link>
</div>
);
}

ReferenceError: Component is not defined

import React from 'react';
import axios from 'axios';
class App extends React.Component {
state = { advice: '' };
componentDidMount() {
this.fetchAdvice();
}
fetchAdvice = () => {
axios.get('https://api.adviceslip.com/advice')
.then((response) => {
const { advice } = response.data.slip;
this.setState({advice});
})
.catch((error) => {
console.log(error);
})
}
render () {
const { advice } = this.state;
return (
<div className="app">
<div className="card">
<h1 className="heading">{advice}</h1>
<button className="button" onClick={this.fetchAdvice}>
<span>Give Me Advice!</span>
</button>
</div>
</div>
);
}
}
export default App;
According to your comment, you are calling App with
<li> <Link href="#advice"> <NavLink onClick={App}>Get an Advice</NavLink> </Link> </li>
The way that you are calling App is wrong. This binds the App as a function to the event onClick. This is not the way to use a React Class Component or React Router Link.
Provide a to parameter value and map it to App in the Route using the Switch statement.
For reference, checkout this example
https://reactrouter.com/web/example/basic
You can't assign a react component to an onClick event. Or i should say to any events. You can't call components like callback functions. That's wrong. React does not support routing with URL change by itself. You should use a third party library called react-router-dom. Here's a link to get you started with react router. https://reactrouter.com/web/guides/quick-start

JSX onClick event seems to be clicked on default

I think I am doing something stupid. I have some code and can't figure out why its not working how I expect it to.
I expect the terminal to log to the terminal when the button / link is clicked but it seems to do it regardless
Code below
import React, { Component } from 'react'
import DataExample from './dataExample'
export default class home extends Component {
state = {
name:"Joy",
place:"nirvana"
}
consoleLog = (e) =>{
return console.log("just clicked")
}
render() {
return (
<div>
<h3>This is my homepage that contains components</h3>
<a href="#" onClick={this.consoleLog("link clicked")}>My Button</a>
</div>
)
}
}
Actual result shows the console.log proir to my clicking button
Currently you are calling the this.consoleLog() in the code instead of passing it.
This should work:
<a href="#" onClick={() => this.consoleLog("link clicked")}>My Button</a>
consoleLog() is calling on the render
return (
<div>
<h3>This is my homepage that contains components</h3>
<a href="#" onClick={() => this.consoleLog("link clicked")}>My Button</a>
</div>
)
}

How Can I conditionally wrap this react component

I am just wondering on how can I avoid duplicating this code when I am conditionally rendering a component.
What I have so far is a navbar component that is connected to redux and it gets state of (isAuth or not) if it's it would render the div with the logout() else it would render the div with login().
Now this approach is not quite good and it's repetitive. I have come across this https://blog.hackages.io/conditionally-wrap-an-element-in-react-a8b9a47fab2 which basically allows you to conditionally render components without duplicating the code but Unfourtnely I was unable to get my head around it. Sorry, I am just learning to react at the moment.
If you please tell me how to use this or if there is an alternative way that i can try that would be very helpfull
Thanks
function Navbar({ isAuth, logOut }) {
if(isAuth) {
return(
<div className="navbar">
<a> link A</a>
<a> link B</a>
<a> link C</a>
<a> link D</a>
<button onClick={() => logOut()} > Logout </button>
</div>
)
}
return (
<div className="navbar">
<a> link A</a>
<a> link B</a>
<a> link C</a>
<a> link D</a>
<button> Login </button>
</div>
)
}
const mapStateToProps = ({ login }) => {
return {
isAuth: login.isAuthenticated
};
};
export default connect(
mapStateToProps,
{ logOut }
)(Navbar);
Just make the button render conditional;
function Navbar({ isAuth, logOut }) {
return(
<div className="navbar">
<a> link A</a>
<a> link B</a>
<a> link C</a>
<a> link D</a>
{isAuth ? <button onClick={() => logOut()} > Logout </button> : <button> Login </button>}
</div>);
}
}
const mapStateToProps = ({ login }) => {
return {
isAuth: login.isAuthenticated
};
};
export default connect(
mapStateToProps,
{ logOut }
)(Navbar);
You can place basic conditions within render/returns wrapped in curly braces - {}. Basically if isAuth is truthy render logout, otherwise login.

How to click an image and reload the current page in 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()
}

Resources