Translate (CSS) not working when clicking on button in vue js - vue-component

I was trying to build a corousel and for that I was trying to translate the div to the left when I click on a button but it is not working.
However when I change the innerStyle to
md:hover:-translate-x-${step.value} it works.
<template>
<div class="max-w-full h-[600px] bg-slate-500 flex flex-col items-center">
<div ref="inner" class="flex overflow-hidden flex-nowrap " :class="innerStyle" >
<div v-for="n in 10" class="shrink-0" :key="n">
<img :src="card" />
</div>
</div>
<div class="h-[50px] w-[100px]">
<button class="h-[50px] w-[50px] bg-white" v-on:click="next">click</button>
</div>
</div>
</template>
<script setup lang="ts">
import card from '../assets/colouselcard.png'
import { onMounted, ref } from 'vue';
const trans = ref("md:-translate-x-");
const step = ref('')
const innerStyle = ref({})
const inner=ref();
function next(){
moveleft()
}
function moveleft(){
innerStyle.value = `md:-translate-x-${step.value}`
}
onMounted(()=>{
const innerWidth = inner.value.scrollWidth // ❶
const totalCards = 10
step.value = '10'
console.log(innerWidth)
})
</script>

Related

feching data dynamically using getServerSideProps in next js but error: Cannot read properties of null (reading 'useContext')

I'm trying to fetch data dynamically according to user choice, here I'm using getServerSide props inside pages/newsPages/[category].tsx
error pointing towards this:
TypeError: Cannot read properties of null (reading 'useContext')
46 export async function getServerSideProps(context: any) {
> 47 | const router = useRouter();
| ^
import { useRouter } from 'next/router'
import React, { useState } from 'react'
import Feeds from '../../components/Feeds'
import Header from '../../components/Header'
export default function category({ newsCategory }:any) {
const [date, setDate] = useState(new Date())
return (
<div className='bg-gray-100'>
<Header />
<main className='mx-5 my-5'>
<div className='bg-white'>
<div className='flex justify-between p-4'>
<h1 className='text-sm font-bold md:text-2xl'>Wellcome to clone BBC.com</h1>
<h1 className='text-sm font-bold md:text-2xl'>{date.toDateString()}</h1>
</div>
{newsCategory.articles.slice(0, 1).map((article:any )=> (
<a key={article.url} href={article.url}
className="relative">
<img className='w-full' src={article.urlToImage ? article.urlToImage: "./ALT.jpg"} alt="" />
<h1
className='text-white absolute bottom-[40%] left-[5%]
lg:text-2xl text-xl'>{article.title}</h1>
<p className='text-white absolute bottom-[30%] left-[5%] line-clamp-1'>{article.description}</p>
</a>
))}
<div className='grid grid-flow-row-dense md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'>{/*grid start*/}
{newsCategory.articles.slice(1, newsCategory.articles.length).map((article: any) => (
<Feeds
url={article.url}
className=""
key={article.url}
urlToImage={article.urlToImage}
title={article.title}
description={article.description}
/>
))}
</div>
</div>
</main>
</div>
)
}
export async function getServerSideProps(context: any) {
const router = useRouter();
const { category } = router.query
const newsCategory = await fetch(`https://newsapi.org/v2/top-headlines?country=us&category=${category}&apiKey=${process.env.API_KEY}`)
.then(res => res.json())
return {
props: {
newsCategory,
}
}
}
pages/index.tsx
import Head from 'next/head'
import Header from '../components/Header';
import NewsFeed from '../components/NewsFeed';
export default function Home({ news }: any) {
return (
<div className='bg-gray-100 '>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<main className='mx-5 my-5'>
<NewsFeed news={news} key={news.article}/>
</main>
</div>
)
}
export async function getServerSideProps(context: any) {
const news = await fetch("https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=")
.then(res=>res.json());
return {
props: {
news,
}
}
}
header.tsx
pushing to the newspages
<p className='hidden hover:text-blue-500 sm:inline-flex'
onClick={()=> router.push("/")}>Home</p>
<p className='hidden hover:text-blue-500 sm:inline-flex'
onClick={()=> router.push("/newsPages/general")}>News</p>
<p className='hidden hover:text-blue-500 sm:inline-flex'
onClick={()=> router.push("/newsPages/sports")}>Sport</p>
<p className='hidden hover:text-blue-500 sm:inline-flex'
onClick={()=> router.push("/newsPages/entertainment")}>Reel</p>
<p className='hidden hover:text-blue-500 sm:hidden lg:inline-flex'
onClick={()=> router.push("/newsPages/health")}>Worklife</p>
<p className='hidden hover:text-blue-500 sm:hidden lg:inline-flex'
onClick={()=> router.push("/newsPages/science")}>Science</p>
<p className='hidden hover:text-blue-500 sm:hidden lg:inline-flex'
onClick={()=> router.push("/newsPages/future")}>Future</p>
what I did wrong here, can I use getServerSideProps in multiple files inside the pages folder? why here this error occurs,

CSS : Text is overflowing from div

I'm using tailwind with react. The problem is that my paragraph text is quite long. I have applied overflow-hidden to the div. But it is still flowing outside div. But it is not visible. But it is ruining my UI. As the pic is also getting stretched out due to the text overflowing. How do I stop the text from overflowing. So I only get the text that is visible inside div. I am using subString(0,50). It will fix the issue, if I use a smaller number. But I want to know is there any other way to fix it. So that the text does not go outside the div and occupies full space of div only. I tried many other properties to fix this issue. But no success so far.
I have uploaded a gif of my problem on imgur
Code
import React, { useEffect, useState } from "react";
import { BsBoxArrowUpRight, BsPencilSquare, BsTrash } from "react-icons/bs";
import { getActors } from "../api/actor";
let currentPageNo = 0;
let limit = 20;
export default function Actors() {
const [actors, setActors] = useState([]);
const [reachedToEnd, setReachedToEnd] = useState(false);
const fetchActors = async (pageNo) => {
const { profiles, error } = await getActors(pageNo, limit);
if (!profiles.length) {
currentPageNo = pageNo - 1;
return setReachedToEnd(true);
}
setActors([...profiles]);
};
const handleOnNextClick = () => {
if (reachedToEnd) return;
currentPageNo += 1;
fetchActors(currentPageNo);
};
const handleOnPrevClick = () => {
if (currentPageNo <= 0) return;
currentPageNo -= 1;
fetchActors(currentPageNo);
};
useEffect(() => {
fetchActors(currentPageNo);
}, []);
return (
<div className="p-5">
<div className="grid grid-cols-4 gap-5">
{actors.map((actor) => {
return <ActorProfile profile={actor} key={actor.id} />;
})}
</div>
<div className="flex justify-end items-center space-x-3 mt-5">
<button
type="button"
className="text-primary dark:text-white hover:underline"
onClick={handleOnPrevClick}
>
Prev
</button>
<button
type="button"
className="text-primary dark:text-white hover:underline"
onClick={handleOnNextClick}
>
Next
</button>
</div>
</div>
);
}
const ActorProfile = ({ profile }) => {
if (!profile) return null;
const [showOptions, setShowOptions] = useState(false);
const handleOnMouseEnter = () => {
setShowOptions(true);
};
const handleOnMouseLeave = () => {
setShowOptions(false);
};
let acceptedNameLength = 15;
const getName = (name) => {
if (name.length <= acceptedNameLength) return name;
return name.substring(0, acceptedNameLength) + "...";
};
const { name, avatar, about = "" } = profile;
return (
<div className="bg-white dark:bg-secondary shadow dark:shadow rounded h-20 overflow-hidden">
<div
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
className="flex cursor-pointer relative"
>
<img
src={avatar}
alt={name}
className="w-20 aspect-square object-cover"
/>
<div className="px-2 flex-1">
<h1 className="text-xl text-primary dark:text-white whitespace-nowrap">
{getName(name)}
</h1>
<p className="text-primary dark:text-white opacity-75">
{about.substring(0, 30)}
</p>
</div>
<Options visible={showOptions} />
</div>
</div>
);
};
const Options = ({ visible, onEditClick, onDeleteClick }) => {
if (!visible) return null;
return (
<div className="absolute inset-0 bg-primary bg-opacity-25 backdrop-blur-sm flex justify-center items-center space-x-5">
{" "}
<button
onClick={onDeleteClick}
type="button"
className="text-primary bg-white p-2 rounded-full hover:opacity-80 transition"
>
<BsTrash />
</button>
<button
onClick={onEditClick}
type="button"
className="text-primary p-2 rounded-full bg-white hover:opacity-80 transition"
>
<BsPencilSquare />
</button>
</div>
);
};

How can fix column property on the next fetch?

This is my first time I am asking question here. If I make any mistake, sorry from now on. I've been trying to build infinite scroll bar with 3 columns. But when the next data is fetched, the images act really weird. I've tried almost everything like "fixed, flex-nowrap", etc.. with tailwind. But none of them worked. I also made research almost for 3 hours and couldn't find any helpful resources. I'd be glad if you could help me!
video: https://streamable.com/ouk16y
import React, { useState, useEffect } from "react";
import InfiniteScroll from "react-infinite-scroll-component";
//components
//icons
import { AiOutlineHeart, AiOutlinePlus } from "react-icons/ai";
//styling
const Gallery = () => {
const apiKey = "apiKey";
const [pictures, setPictures] = useState([]);
const [page, setPage] = useState(1);
//fetching the api data
useEffect(() => {
fetch(
`https://api.unsplash.com/search/photos?page=${page}&query=office&client_id=${apiKey}`
)
.then((resp) => {
return resp.json();
})
.then((data) => {
const pictureData = [...new Set(data.results)];
setPictures((prev) => [...prev, ...pictureData]);
});
}, [page]);
return (
<InfiniteScroll
dataLength={pictures.length}
next={() => setPage((prev) => prev + 1)}
hasMore={true}
scrollThreshold={0.3}
>
<div className="columns-1 lg:columns-3 col-auto lg:w-5/6 mx-auto gap-8 space-y-4">
{pictures.map((picture) => (
<div className="" key={picture.id}>
<div className="flex p-2 lg:hidden ">
<img
className="rounded-full w-10 h-10"
src={picture.user.profile_image.medium}
alt={`${picture.name} profile`}
/>
<span className="pt-2 pl-2">{picture.user.name}</span>
</div>
<img className="resize-none" src={picture.urls.regular} />
{/* //icons for small devices// */}
<div className="flex mt-2 pl-2 mb-8 lg:hidden">
<AiOutlineHeart className="w-8 h-8 text-gray-600" />
<AiOutlinePlus className="w-8 h-8 ml-2 text-gray-600 " />
<button className="w-40 border ml-auto mr-4">Download</button>
</div>
</div>
))}
</div>
</InfiniteScroll>
);
};
export default Gallery;
'''

How set cards in a row using react bootstrap

I want to add card using react-bootstrap in a project. I used Grid and CardDeck option from react-bootstrap. But all cards comes in a column (like this). But I want this cards comes with side by side, not in row.(I want my output like this image).
Here the code for card section
import Card from 'react-bootstrap/Card';
const Course = (props) => {
const {title, price,details,img} = props;
return (
<div>
<div className="col-md-4 col-12 mt-5 mx-auto">
<Card>
<Card.Img variant="top" src={img} />
<Card.Body>
<Card.Title>{title}</Card.Title>
<Card.Title>{price}</Card.Title>
<Card.Text>
{
details
}
</Card.Text>
</Card.Body>
</Card>
</div>
</div>
);
};
export default Course;
Where I pass the value
import React from "react";
import fakeData from "../FakedData/FakeData";
import Course from "../Course/Course";
import CardDeck from 'react-bootstrap/CardDeck';
const Home = () => {
return (
<div>
<div className="container">
<div className="row">
<CardDeck>
{fakeData.map((data) => {
return (
<Course
key={data.id}
title={data.title}
price={data.price}
details={data.details}
img={data.img}
/>
);
})}
</CardDeck>
</div>
</div>
</div>
);
};
export default Home;
I don't try this, it's the old way with modulo, should work, but not responsive
const Home = () => {
const numInRow = 4;
return (
<div>
<div className="container">
<div class="d-flex justify-content-center"> // <---- div first row
{fakeData.map((data, idx) => { //<--- note the idx
return (
<Course
key={data.id}
title={data.title}
price={data.price}
details={data.details}
img={data.img}
/>
{idx % numInRow === 0 && </div><div class="d-flex justify-content-center">} // <--- use modulo to close row and open a new one
);
})}
</div> //<-- div last row
</div>
</div>
);
};

React-bootstrap modal adding margin or padding

I have added a modal to display a login pop-up.
My issue is that the Modal itself seems having padding internally which break my user experience.
As you can see below in the image:
Adding a link as I am not able to attached the image. https://photos.app.goo.gl/iJZRZ28o8dQhmJh4A
[enter link description here][1]
and below the code
import React from "react";
import { Modal } from "react-bootstrap";
import '../../assets/styles/Login.css';
class LoginRegisterModal extends React.Component {
constructor(props, context) {
super(props);
this.state = {show: false};
}
....
render() {
const styleModal = {
marginTop: "15%",
marginLeft: "30%",
padding: 0,
width:770,
height:480,
backgroundColor:"#ffffffff",
borderRadius:21.5,
}
const signUpButton = document.getElementById('signUp');
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () => {
container.classList.add('right-panel-active');
});
signInButton.addEventListener('click', () => {
container.classList.remove('right-panel-active');
});
return (
<Modal show={this.state.show} style={styleModal} >
<div class="container" id="container">
<div>
.....
</div>
<div class="overlay-container">
<div class="overlay">
<div class="overlay-panel overlay-left">
<h1>Sign in.</h1>
<p>
Nice to see you again.Login and continue the journey.
</p>
<button class="ghost" id="signIn">Sign In</button>
</div>
<div class="overlay-panel overlay-right">
<h1>Hey, new friend!</h1>
<p>New to the Village? Sign up and start your journey</p>
<button class="ghost" id="signUp">Sign Up</button>
</div>
</div>
</div>
</div>
</Modal>
);
}
}
export default LoginRegisterModal;```
I have tried to remove all my containers and just display a simple text using `<p> test </p>` and I am facing the same issue. The `marginTop` and `marginLeft` defined in the style allowed my to move the Modal from the top left corner.
Any idea why I have some margin inside the modal ?
[1]: https://photos.app.goo.gl/iJZRZ28o8dQhmJh4A

Resources