Home > OS >  If I am using onclick to a button why it redirects me to the same page i am in (reactjs)
If I am using onclick to a button why it redirects me to the same page i am in (reactjs)

Time:12-04

how to click on anchor tag in the card and redirects me to another page with more details of the current card example click on opens new tab with current (clicked) card details here is an api for item https://api.npoint.io/d275425a434e02acf2f7/News/0

snippets of code also a link that works https://codesandbox.io/s/sweet-spence-1tl4y5?file=/src/App.js

my api https://api.npoint.io/d275425a434e02acf2f7 for rendering all items in cards

 filteredCat?.map((list) => {
              if (list.showOnHomepage === "yes") {
                const date = format(
                  new Date(list.publishedDate),
                  "EEE dd MMM yyyy"
                );
                const showCat = news.map((getid) => {
                  if (getid.id == list.categoryID) return getid.name;
                });
                //  const rec = list.publishedDate.sort((date1, date2) => date1 - date2);

                return (
                  <Card
                    className=" extraCard col-lg-3"
                    style={{ width: "" }}
                    id={list.categoryID}
                  >
                    <Card.Img
                      variant="top"
                      src={list.urlToImage}
                      alt="Image"
                    />
                    <Card.Body>
                      <Card.Title className="textTitle">
                        {list.title}
                      </Card.Title>
                      <Card.Text></Card.Text>
                      <small className="text-muted d-flex">
                        <FaRegCalendarAlt
                          className="m-1"
                          style={{ color: "#0aceff" }}
                        />
                        {date}
                      </small>

                      <div
                        style={{ color: "#0aceff" }}
                        className="d-flex justify-content-between"
                      >
                        <Button variant="" className={classes["btn-cat"]}>
                          {showCat}
                        </Button>
                        <div>
                          <FaRegHeart />
                          <FaLink />
                        </div>
                      </div>
                    </Card.Body>
                  </Card>
                );
              }
            })
          }
        </div>
      }

I tried this technique but it does direct me to the same page not the new tab with empty page !!

function handleClick(event) {
  event.preventDefault();
  window.location.href = 'src/comp/newsitem';
}

function news() {
  return (
    <a href="#" onClick={handleClick}>
      Click me to redirect!
    </a>
  );
}

CodePudding user response:

To open a new tab with a specified URL, you can use the window.open() method in JavaScript. Here's an example of how you could do this:

function handleClick(event) {
  // prevent the default action of the anchor tag, which is to navigate to the specified URL
  event.preventDefault();

  // open a new tab with the specified URL
  window.open('src/comp/newsitem', '_blank');
}

function news() {
  return (
    <a href="#" onClick={handleClick}>
      Click me to redirect!
    </a>
  );
}

Alternatively, you can use the target attribute on the a tag to specify that the link should be opened in a new tab. Here's an example of how you could do this:

function news() {
  return (
    <a href="src/comp/newsitem" target="_blank">
      Click me to redirect!
    </a>
  );
}

Hope this help!

CodePudding user response:

React provides SPAs which means that you can load your content of different pages without any refresh or redirect. So no need to redirect to another page unless you really want to open the page in a new tab.

Also if you want to have multiple page paths, you should use react-router-dom.

So first of all you should add your routes to your app. Add a pages.js file with this content:

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import App from './App';
import News from './News';
import NewsItem from './NewsItem';

function Pages() {

  return (
    <BrowserRouter>
      <Routes>
        <Route path='/news' element={<News />} />
        <Route path='/newsItem' element={<NewsItem />} />
        <Route path='/' element={<App />} />
      </Routes>
    </BrowserRouter>
  );
}

export default Pages;

And then import it to your index.js file:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import Pages from "./Pages";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <Pages />
  </StrictMode>
);

NewsItem file:

function NewsItem() {
  return <div>News Item</div>;
}
export default NewsItem;

And finally when you want to navigate the News page, do this:

import { Link } from 'react-router-dom' 
<Link to='/news' />

Or if you want to open in new tab:

<Link to='/news' target='_blank' />

And for navigating to NewsItem page (without any a tag):

<Link to="/newsItem">News Item</Link>
  • Related