button not going to correct links - reactjs

I am using react and doing my portfolio
when people click on the button to view my github repo or project it goes to the wrong place
const Project = () => {
return (
<div className='work-container'>
<h1 className='project-heading'>Projects</h1>
<div className='project-container'>
{ProjectData.map((val, ind) => {
return (
<ProjectCard
key={ind}
imagesource={val.imagesource}
title={val.title}
text={val.text}
view={val.view}
github={val.github}
/>
)
})}
</div>
</div>
)
}
this is what my data file contains
const ProjectData = [
{
imagesource: project1,
title: 'Diamond Devs Tech Blog',
text: 'A community of developers who can write blogs about code or ask questions Built out of a need for developers have a nice simple platform rather than the complex ones out there in the marketplace, this was for an assignment foor my Bootcamp was challenging as had to do the front and backend from scratch using tech that I am still getting used too.',
view: 'https://diamond-developers-tech-blog.herokuapp.com/',
github: 'https://github.com/breakfireaus/diamond-developers-tech-blog',
},
]
export default ProjectData
I tried the above and instead of going to view project or github it goes to for example
https://matthew-younger-portfolio.herokuapp.com/portfolio/https://diamond-developers-tech-blog.herokuapp.com/
instead of just
https://diamond-developers-tech-blog.herokuapp.com/

I have reviewed code from you github repo. What you are doing is using React router NavLink to move to an external website which you cannot do as you can use it move within your application Documentation
.
You can convert them to a tag in your Project Card and they will work fine. You can use target="_blank" if you want to open the link in new tab.
import "./ProjectCardStyle.css";
import React from "react";
import { Link } from "react-router-dom";
const ProjectCard = (props) => {
return (
<div className="project-card">
<img src={props.imagesource} alt="Project Imagery" />
<h2 className="project-title">{props.title}</h2>
<div className="project-details">
<p>{props.text}</p>
<div className="project-buttons">
<a target={"_blank"} href={props.view} className="btn">
VIEW
</a>
<a target={"_blank"} href={props.github} className="btn">
Github
</a>
</div>
</div>
</div>
);
};
export default ProjectCard;

Related

How to solve react hydration error in Nextjs

I have created small nextjs page using wordpress REST API, Now react-hydration-error error show this page.I am using react html parser npm. How do I solve this error. could you please solve this error.
my code:
import Image from 'next/image'
import React ,{Component}from 'react'
import Link from 'next/link';
import { BiCalendar } from "react-icons/bi";
import ReactHtmlParser from 'react-html-parser';
export default class Blog extends Component{
constructor(props){
super(props);
this.state={
data: props.bloglist,
isLoading: true,
dataLoaded: false,
};
}
render(){
if (!this.state.data) {
return null;
}
console.log(this.state.data)
return(
<>
<div className="container blog-section">
<div className='row'>
<h2>Latest Posts</h2>
</div>
<div className='row'>
{
this.state.data.map(((x,i) =>(
<div className='col-md-4 boxs text-center' key={i}>
<div className='bg-info'>
<img src={x.images.large} className='img-fluid'/>
<h3>{x.title.rendered} </h3>
<p className='shopping'><span><BiCalendar/> {x.date}</span> </p>
{/* <p dangerouslySetInnerHTML={{__html: x.excerpt.rendered}}></p><span><BiShoppingBag/> {x.slug}</span> */}
<p class='expert'>{ReactHtmlParser(x.excerpt.rendered)}</p>
<Link href={"/blog"+"/"+x.slug+"/"+x.id } passHref={true}><p className='readmore'><span>Readmore </span></p></Link>
</div>
</div>
)))
}
</div>
</div>
</>
)
}
}
My original issues:
paragraph coming this format <p>If you have heard that there are ways to make money while shopping in the UAE and would lik</p> from API, So I converted to html.
I had this error, in my case I had <p> tag nested inside another <p> tag,
I was using Typography (MUI v5) to render text, switching to <Box> from <Typography> fixed the error.
We use components to build the React-based websites, These components are made using HTML tags. It is very important not to nest the same HTML elements.
For Example:
function Logo() {
return (
<Link href="/">
<a>
<Image
src="/images/logo.svg"
width={100}
height={75}
/>
</a>
</Link>
);
}
export default Logo;
Above is the Logo Component which has already the <a></a> tag inside it.
In this example, you will get the React Hydration Error if the <a> tag is used inside another <a> tag.
<a href="#">
<Logo />
</a>
So do not include the same HTML tags, which are hidden inside the
components to avoid react hydration error.
In my case I am using NextJS and I had a dropdown with react-select, the default value was changing after a small calculation, that does not like to nextjs, this is my previous code:
<Select options={seasons}
onChange={() => setSeason(e.value)}
defaultValue={seasons.find((x) => x.value == season) ? seasons.find((x) => x.value == season) : seasons[0]}
/>
So, I changed that calculation to the useEffect and initialized the react-select dropdown only when that value was calculated,now this is my current code that works:
{defaultSeason && (<Select options={seasons}
onChange={() => setSeason(e.value)}
defaultValue={defaultSeason}
/>)}
So, basically check that the defaultValue or anything else does not change after the html is sent to the client part in NextJS.
Follow these: https://nextjs.org/docs/messages/react-hydration-error
Or try deleting <a> within <Link> maybe.
My first code was this:
const isUserLoggedIn = is_user_logged_in()
// is_user_logged_in() checks for cookie of user token and returns boolean
Got the error about hydration
Then changed code to this:
const [isUserLoggedIn, setIsUserLoggedIn] = useState(null)
useEffect(() => {
setIsUserLoggedIn(is_user_logged_in())
}, [])
Renders was like this:
{isUserLoggedIn ? (
<>
{/* After login */}
<Profile USER={USER}/>
</>
) : (
<>
{/* Before login */}
<SigninButtons/>
</>
)}
And error solved
You can also check this
https://nextjs.org/docs/messages/react-hydration-error
Just try restarting the server. npm run dev. It worked for me. I was using react-hot-toaster.
Also try to check if you have sth like this:
<p>
<div>
Hello
</div>
</p>
div cant be inside p tag

How do I consume data from a component where I am passing data using Link of react-router in class Components?

I have a carousel of cards. And each card has some data which if I click on the button on the card. I want to render the details of that particular card in different components on a different page which is item-details.
How do I achieve this in class components? There is an id in the map can I send using that in the details page where I am trying to render the full details of the card.
{this.state.data.map((item, idx) => {
return (
<div key={`edth_${idx}`} className="col-12 col-sm-6 col-lg-4 item explore-item" data-groups={item.group}>
<div className="card">
<div className="image-over">
<img className="card-img-top" src={item.img} alt="" />
</div>
<div className="card-caption col-12 p-0">
<div className="card-body">
<a href="/item-details">
<h5 className="mb-0">{item.title}</h5>
</a>
<div className="card-bottom d-flex justify-content-between">
<span>{item.price}</span>
<span>{item.count}</span>
</div>
<Link to={{pathname: '/item-details',state: [{img:'item.img',count: 'item.count', title: 'item.title', price: 'item.price'}]}} className="btn btn-bordered-white btn-smaller mt-3"> <i className="icon-handbag mr-2" />Check it out</Link>
</div>
</div>
</div>
</div>
);
})}
</div>
I have added the Link from react router instead of, but I still don't know how to consume this in the component which will be in /item-details.
Found out that instead of useLocation, I can use with router in class components so...
Imported useRouter in the item-details page and consuming like this in the render():
render() {
const { location } = this.props;
return (
<div className="item-info">
{location && location.img && <div className="item-thumb text-center">
<img src={location.img} />
</div>}
);
By doing this, I am not getting any error. But the img is not showing.
React is generally used for a single paged application (i.e. you wouldn't be sending users to different URLS) unless you are using something like NEXT, React Router, etc. for handling different pages.
Instead of sending the user to another page, you would render a new component with the details sent as a prop.
But if you're asking how to send information from a component to another page, i would suggest you look into React Router, which is designed to do this.
I'm not sure if this is actually what you're asking though so please provide further details on what your project is made up of.
In my experience, the best way to handle this would be to set the URL query when the onClick() handler is run. The view would update & the details would be fetched as needed. That way if you your homepage is mysite.com you can get more details by visiting mysite.com/moreinfo.
To accomplish this, you can use react-router-dom history API:
import { useHistory } from "react-router-dom";
function myComponent() {
let history = useHistory();
function handleClick() {
history.push("/moreinfo");
}
return (
<button type="button" onClick={handleClick}>
View More Info
</button>
);
}

React Icons - pull icon dynamically

I'm using React Icons and it works great, but would it be possible to dynamically pull an icon from a React loop? For example, let's say I have this code:
import { FaCodepen, FaLinkedinIn, FaGithub } from 'react-icons/fa'
[...]
const data = useStaticQuery(graphql`
query SocialQuery {
allContentfulSocial {
edges {
node {
title
link
icon
}
}
}
}
`)
[...]
<div className="column is-half">
<div className="level social-icons">
{
data.allContentfulSocial.edges.map((edge) => (
<div className="level-item">
<a
href={edge.node.link}
target="_blank"
rel="noopener noreferrer"
title={edge.node.title}
>
<FaCodepen /> // <-- is it possible to dynamically pull an icon here?
</a>
</div>
))
}
</div>
</div>
So in my case, I have three social icons, namely: CodePen, GitHub, and LinkedIn. I was thinking of doing something like this from the code above:
<edge.node.icon />
But this didn't work since it threw an error. I was thinking they would have a use-case somewhere in their documentation, but I didn't find anything useful.
Would anyone have run across this issue before? Appreciate the help!
Note: I am using GatsbyJS for my project, which is why there is a GraphQL query above pulling from my Contentful CMS.
You can do it with a simple keyed object:
const icons = {
codepen: FaCodepen,
linkedIn: FaLinkedIn,
...
}
const PostIcon = ({iconName}) => {
const Icon = icons[iconName];
return <Icon />
}

React Web App Routing Works on Desktop (incl. Mobile Dev View), but not on Mobile Browsers

I'm really stuck on a problem with a React web app I'm building. I'm using the array.map() method to dynamically create dropdowns, and I'm finding that everything works beautifully on desktop browsers (including in the mobile view of Chrome dev tools), but not on actual mobile browsers. I would really appreciate your thoughts!
Expected Behavior
I expect the dropdowns to populate, usually from an array of objects. Then, when the user clicks on one of the items in the dropdown menu, it will either trigger (1) a function or (2) a link to another part of the React App. Note that I'm using react-router-dom to handle routing.
Observed Behavior on Mobile Browsers
The dropdowns populate correctly, but they malfunction when I select from among the options (see Figure 1).
This behavior is observable when the dropdown selection triggers both a (react-router-dom Component) and calls a function. In the limited cases when the function is called correctly, the correct parameters are passed and the function does execute correctly.
Code Snippits
This is an example of the code I'm using to generate the list of links. It is a simple React functional component that serves as the header to all settings pages in my app, and the Component is part of a React MaterializeCSS library, which seems to be working fine.:
const SettingsHeader = () => {
let { url } = useRouteMatch();
const { userAccess, styleItem, headerStyle, updateHeader, theme } = useContext(SettingsContext);
const options = userAccess.length ? (
userAccess.sort().map(permission => {
// Returns an object with details needed to build the component via a Settings Context function.
let details = styleItem(permission);
return (
<Link
key={permission}
to={`${url}${details.link}`}
onClick={() => updateHeader(permission)}
>
<Icon className={theme.text}>{details.icon}</Icon>
<span className={theme.text}> {details.text}</span>
</Link>
);
})
) : (
<h4 className="grey-text">
<Icon>warning</Icon> You don't have permission to edit any settings.
</h4>
);
return (
<h4 className={theme.text}>
<i className="material-icons">{headerStyle.icon}</i> {headerStyle.text}
<Dropdown
options={{ ... }}
trigger={
<Button className={"right " + theme.themeColor} node="button">
Views
</Button>
}
>
{options}
<a href="#!">
<Icon className="grey-text">close</Icon>
<span className="grey-text"> Close</span>
</a>
</Dropdown>
</h4>
);
}
This is an example of the code I'm using to generate a list of theme options, each of which calls a function in a React Context Component I'm using in many places in the App:
const ThemeSettings = () => {
// Brings in Theme update function from SettingsContext
const { changeTheme, theme } = useContext(SettingsContext);
// Array of possible themes.
const themesList = ['Burnt Orange', 'Chrome', 'Deep Purple', 'Earth', 'Fresh Green', 'Green', 'Maroon', 'Navy', 'Pink', 'Red', 'Royal Blue', 'Teal']
const themeOptions = themesList.map(theme => {
let themeObject = getTheme(theme);
return (
<a href="#!" key={theme} onClick={(e) => changeTheme(e, theme) }>
<Icon className={themeObject.text}>style</Icon>
<span className={themeObject.text}> {theme}</span>
</a>
)
});
return (
<Dropdown
options={{ ... }}
trigger={
<Button className={"left " + theme.themeColor} node="button">
Themes
</Button>
}
>
{ themeOptions }
<a href="#!">
<Icon className="grey-text">close</Icon>
<span className="grey-text"> Close</span>
</a>
</Dropdown>
);
}
Thanks very much for giving this a look!
This is a known MaterializeCSS bug for devices running iOS-13.
I was only able to find one workaround available at time of writing, mentioned by Falk in this issue thread:
To fix it, I had to check out the #v1-dev branch of
https://github.com/Dogfalo/materialize, build it with grunt release
and use the materialize.js in /dist folder for my project.

How to embed an HTML/script snippet into a react.js page without jQuery?

I created a react website using create-react-app. In one of the pages, I want to embed an airbnb preview, see below code and screenshot provided by airbnb.
How can I insert this code into my React components? (NB I don't want to use jQuery)
<div
class="airbnb-embed-frame"
data-id="21917882"
data-view="home"
data-hide-price="true"
style="width:450px;height:300px;margin:auto"
>
<a href="https://www.airbnb.com/rooms/21917882?s=51">
<span>View On Airbnb</span>
</a>
<a
href="https://www.airbnb.com/rooms/21917882?s=51"
rel="nofollow"
>T2 hypercentre Capitole/St-Sernin, quiet & bright
</a>
<script async="" src="https://www.airbnb.com/embeddable/airbnb_jssdk" />
</div>;
The component created by this code, which I want to embed in the react page
This does go quite against React principles, but you could load the embed script with something like react-async-script-loader (or a custom solution) and then call the provided AirbnbAPI.bootstrap() function on render or when the component mounts.
💻 Live Example
import React, { Component } from "react";
import scriptLoader from "react-async-script-loader";
const Preview = ({ isScriptLoaded, isScriptLoadSucceed }) => {
if (isScriptLoaded && isScriptLoadSucceed) {
window.AirbnbAPI.bootstrap();
}
return (
<div
className="airbnb-embed-frame"
data-id="21917882"
data-view="home"
data-hide-price="true"
style={{ width: 450, height: 300, margin: "auto" }}
>
<a href="https://www.airbnb.com/rooms/21917882?s=51">
<span>View On Airbnb</span>
</a>
<a href="https://www.airbnb.com/rooms/21917882?s=51" rel="nofollow">
T2 hypercentre Capitole/St-Sernin, quiet & bright
</a>
</div>
);
};
export default scriptLoader(["https://www.airbnb.com/embeddable/airbnb_jssdk"])(
Preview
);

Resources