Change react.js(multi page app) with button element? - javascript

beginner with react.js. My goal is to switch pages in my app. I have made this component for export into another:
const component = ({ name, email, id }) => {
return (
<button href="secondContent.html" onclick="secondContent()" id="component">
<div>
header
</div>
</button>
);
}
Function of this button was meant to be a switcher to second page (secondComponent).
I also have been trying to deal with html page to (actually) create that secondComponent file.
After trying to switch by this button for a few times, I could not get a result which I wanted.
If annyone can brief me with a proper way to solowe this problem and sugest me a better solution, pls help.
Thanks in advance. :)

There are a number of ways this can be achieved however for a simple sitatuion like this, you could do something like:
const component = ({name, email, id}) => {
const gotoSecondContent = () => {
window.location = "secondContent.html";
}
return (
<button onclick={ gotoSecondContent } id="component">
<div>header</div>
</button>);
}

You should check the react-router-dom documentation. I think you will find all you need there !
https://reacttraining.com/react-router/web/guides/philosophy

Related

How to render a new popup every time I clicked Grid?

The problem is...
The first popup renders fine.
But when I try to render the second popup, it's not working.
A new popup is not invoked, the previous popup is refreshed.
I want to call a new popup when I clicked a cell in the grid.
my code is like this
const Main = () => {
const [isPopupOpen, setIsPopupOpen] = useState(false);
return (
<>
... other components (including grid)
{ isPopupOpen && <Popup />}
</>
)
};
when Grid is Clicked, 'isPopupOpen' is updated to true.
I use 'react-new-window' library, and this library use 'window.open()' ((https://github.com/rmariuzzo/react-new-window)
so I set different window names to call several popups.
but I can't solve the problem.
I try to set a state object that has a boolean value.
const [popupObj, setPopupObj] = useState({});
when the grid is clicked, popupObj updates like
{'cellA': true, 'cellD': true}
and a return statement is like
{popupObj[cellName] && <Popup /> }
but the result was the same.
what should I do to solve this problem?
I wrote an example for you. Hope it helps.
use popupIds state to store the popups that you want to open
use Set to toggle the popupIds in the addPopup click handler
import * as React from "react";
export default function App() {
const [popupIds, setPopupIds] = React.useState([]);
const addPopup = (popupId) => {
const set = new Set(popupIds);
if (set.has(popupId)) {
set.delete(popupId);
} else {
set.add(popupId);
}
setPopupIds(Array.from(set));
};
return (
<div className="App">
{["hello", "react"].map((popupId) => (
<div onClick={() => addPopup(popupId)}>{popupId}</div>
))}
{popupIds.map((popupId) => (
<Popup title={getPopupTitle(popupId)} />
))}
</div>
);
}
const getPopupTitle = (popupId) => `title for ${popupId}`;
const Popup = ({ title }) => <div>{title}</div>;
Here is a codesandbox that you can play with directly.
You need to add your popup in an array, so you can render many popup as you want, then you need to define in How much time you will remove a added popup from array or add a close button
Extra: you can configure in global state to access in all your application to your popups and you will have a component like this: https://www.npmjs.com/package/notistack

How would I use a button w/onClick to change a value that is here used in a useEffect hook?

I want to be able to change what is the "feed" in this with a button, not having to swap to a new page. I have the two values, with the "home" being the one that shows all blogs, and personal being just the ones with the author value of "mario". What would I have to do add to have the button onClick switch to using the personal filtered blogs. (and defaulting to the home, and if needed a button that changes the current listed blogs back to the home)
(I apologize for any like, poor conventions or anything, I am new to javascript, and well it is javascript)
const Home = () => {
const [viewCount, setViewCount] = useState(0);
const {data: blogs, isPending } = useFetch();
const history = useHistory();
const [newBlog, setNewBlog] = useState([]);
useEffect(() => {
const getNewBlog = async () => {
const home = blogs
const personal = blogs.filter((blog) => blog.author === 'mario')
setNewBlog(home)
}
getNewBlog()
},[]);
return (
<div className="home">
<div className="profile">
<h2>Hello, User!</h2>
<div className="profile-picture"> </div>
<p>Profile Views: {Math.round(viewCount / 2)}</p>
<a href="/">
<button onClick={null}>Manage Your Blog</button> // <-- the onClick that I mention
</a>
</div>
<div className="feed">
{isPending && <div>Loading... </div>}
{ blogs && <BlogList blogs={newBlog} title = "Your Feed"/> }
</div>
</div>
);
}
This isn't the full extent of what I have tried, I tinkered with some other stuff but looking back at it I was going at it with poor logic.
To cover what is expected to happen:
The default "feed" shows all blogs, onClick of the button, it switches over to just the blogs of the author 'mario'. Returning to the default feed could be done through another button, or just a refresh of page.
You just have to add one line in order to filter the blogs on click.
<button onClick={()=>setNewBlog([...blogs.filter((blog) => blog.author === 'mario')])}>Manage Your Blog</button>
I hope this helps, or comment if your expectation is different

How to show a Modal once onShowMoreClick is clicked?

<OneProfileKeyCard
title="Qualification"
showMoreText="See all qualifications"
onShowMoreClick={() => console.log('show more')}
>
Creating, communicating, and implementing the organization&apos;s vision, mission, and overall direction Leading the development and implementation of the overall organization&apos;s strategy.
</OneProfileKeyCard>
import React from 'react'
import './OneProfileKeyCard.scss'
type Props = {
title: string
showMoreText: string
onShowMoreClick: () => void
}
export const OneProfileKeyCard: React.FC<Props> = ({
title,
showMoreText,
onShowMoreClick,
children
}) => (
<div className="one-profile-key-card">
<h3>{ title }</h3>
<div>
{ children }
</div>
<button type="button" onClick={onShowMoreClick}>
{ showMoreText }
</button>
</div>
)
could anyone help me to set up a modal? Im trying to set up a modal once onShowMoreClick is clicked that would turn the children(creating, communicating, and implementing the organization...) into a modal. So far it looks like this:
You will need to have a state-managed in the parent component of where the OneProfileKeyCard child component is called from.
Something like this
const Parent = () => {
const [modalOpen, setModalOpen] = React.useState(false)
return (
<div>
<h1>Demo</h1>
<OneProfileKeyCard
title="Qualification"
showMoreText="See all qualifications"
onShowMoreClick={() => setModalOpen(!modalOpen)}>
text ... text
</OneProfileKeyCard>
</div>
)
}
I'm not sure what else is within your components, but you'll then need a way to close the model, right now I have set the showMoreClick prop to open/close, but if that should open then set it to true and do a similar pass-through for a closing false function.

React Link to open new tab

I Have a React link in my material table.
actions={[
rowData => ({
icon: () => <Link style={{ fontSize:"15px" ,fontSize:'15px'}} to={{pathname:'/VV',state: rowData }} >View</Link> ,
onClick: (rowData)
})
]}
I want to be able to open a new tab on the click.
But my child objects keep getting Cannot read properties of undefined when i decide to open it in a new tab
Please can i have some assistance i've been stuck on this problem.
There is a simple way you can do that without React-Router library,
Make a Link component like blow and use it.
const Link = () => {
const linkRef = useRef(null)
const handleClick = () => {
linkRef.current.link.click()
}
return (
<div ref={linkRef} onClick={handleClick}>
Go to google!
</div>
)
}
You can put the link you want in href and render the Link component where you want! also you can give it a style you want cuz it's a component! :D
I hope you find an answer!

How to save a component state after re-rendering? React js

There are some movie cards that clients can click on them and their color changes to gray with a blur effect, meaning that the movie is selected.
At the same time, the movie id is transferred to an array list. In the search bar, you can search for your favorite movie but the thing is after you type something in the input area the movie cards that were gray loses their style (I suppose because they are deleted and rendered again based on my code) but the array part works well and they are still in the array list.
How can I preserve their style?
Search Page:
export default function Index(data) {
const info = data.data.body.result;
const [selectedList, setSelectedList] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
return (
<>
<main className={parentstyle.main_container}>
<NavBar />
<div className={style.searchbar_container}>
<CustomSearch
onChange={(e) => {
setSearchTerm(e.target.value);
}}
/>
</div>
<div className={style.card_container}>
{info
.filter((value) => {
if (searchTerm === '') {
return value;
} else if (
value.name
.toLocaleLowerCase()
.includes(searchTerm.toLocaleLowerCase())
) {
return value;
}
})
.map((value, key) => {
return (
<MovieCard
movieName={value.name}
key={key}
movieId={value._id}
selected={selectedList}
setSelected={setSelectedList}
isSelected={false}
/>
);
})}
</div>
<div>
<h3 className={style.test}>{selectedList}</h3>
</div>
</main>
Movie Cards Component:
export default function Index({ selected, movieName, movieId, setSelected }) {
const [isActive, setActive] = useState(false);
const toggleClass = () => {
setActive(!isActive);
};
useEffect(()=>{
})
const pushToSelected = (e) => {
if (selected.includes(e.target.id)) {
selected.splice(selected.indexOf(e.target.id), 1);
console.log(selected);
} else {
selected.push(e.target.id);
console.log(selected);
console.log(e.target);
}
setSelected([...selected]);
toggleClass();
};
return (
<div>
<img
className={isActive ? style.movie_selected : style.movie}
id={movieId}
name={movieName}
src={`images/movies/${movieName}.jpg`}
alt={movieName}
onClick={pushToSelected}
/>
<h3 className={style.title}>{movieName}</h3>
</div>
);
}
I can't directly test your code so I will assume that this is the issue:
Don't directly transform a state (splice/push) - always create a clone or something.
Make the setActive based on the list and not dependent. (this is the real issue why the style gets removed)
try this:
const pushToSelected = (e) => {
if (selected.includes(e.target.id)) {
// filter out the id
setSelected(selected.filter(s => s !== e.target.id));
return;
}
// add the id
setSelected([...selected, e.target.id]);
};
// you may use useMemo here. up to you.
const isActive = selected.includes(movieId);
return (
<div>
<img
className={isActive ? style.movie_selected : style.movie}
id={movieId}
name={movieName}
src={`images/movies/${movieName}.jpg`}
alt={movieName}
onClick={pushToSelected}
/>
<h3 className={style.title}>{movieName}</h3>
</div>
);
This is a very broad topic. The best thing you can do is look up "React state management".
As with everything in the react ecosystem it can be handled by various different libraries.
But as of the latest versions of React, you can first start by checking out the built-in tools:
Check out the state lifecycle: https://reactjs.org/docs/state-and-lifecycle.html
(I see in your example you are using useState hooks, but I am adding these for more structured explanation for whoever needs it)
Then you might want to look at state-related hooks such as useState: https://reactjs.org/docs/hooks-state.html
useEffect (to go with useState):
https://reactjs.org/docs/hooks-effect.html
And useContext:
https://reactjs.org/docs/hooks-reference.html#usecontext
And for things outside of the built-in toolset, there are many popular state management libraries that also work with React with the most popular being: Redux, React-query, Mobx, Recoil, Flux, Hook-state. Please keep in mind that what you should use is dependant on your use case and needs. These can also help you out to persist your state not only between re-renders but also between refreshes of your app. More and more libraries pop up every day.
This is an ok article with a bit more info:
https://dev.to/workshub/state-management-battle-in-react-2021-hooks-redux-and-recoil-2am0#:~:text=State%20management%20is%20simply%20a,you%20can%20read%20and%20write.&text=When%20a%20user%20performs%20an,occur%20in%20the%20component's%20state.

Categories

Resources