How can I use same prop in multiple functional components in react - javascript

This is my App.jsx:
import React from 'react';
import SoltM from './slot';
const App = ()=>{
return(
<>
<div>
<SlotM x="emoji1" y="emoji1" z="emoji1" />
<hr />
<SlotM x="emoji2" y="emoji3" z="emoji3" />
<hr />
<SlotM x="emoji3" y="emoji3" z="emoji3" />
<hr />
</div>
</>
)
}
export default App;
This is my SlotM.jsx component, in this, props are not displayed in True or False component.
import React from 'react';
const SlotM = (props) => {
return ( (props.x === props.y && props.y === props.z) )}
const True = (props) => {
let { x, y, z } = props
return (
<>
<div className="slot_inner">
<h1> {x} {y} {z} </h1>
<h1> This is Matching </h1>
</div>
</>
)
}
const False = (props) => {
let { x, y, z } = props
return (
<>
<div className="slot_inner">
<h1> {x} {y} {z} </h1>
<h1> This is not Matching. emoji1 </h1>
</div>
</>
)
}
export default SlotM;
This is my app.jsx
2:This is SlotM.jsx component in this props are not being displayed in True and False component

You can use spread operator like this:
<True {...props} /> <False {...props} />

I think you misunderstood sth. props.x === props.y && props.y === props.z) ) returns boolean value, not Function. How about this?
const SlotM = (props) => {
return (props.x === props.y && props.y === props.z) ? <TrueC {...props}/>: <FalseC {...props}/>
}
const TrueC = (props) => {
...
const FalseC = (props) => {
...

Related

How to use if else condition with variable in Reactjs

I am working in Reactjs. Right now I am getting the current url/hostname. Now I want to use this URL with an if-else condition, which means I just want if url="/"(home page) then the first header should display otherwise second word should display. In other words, I want to know how we can use if-else condition with dynamic variable?
Here is my current code
import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url =router.asPath;
return (
<>
<div>
//need to use if else condition based on "url" variable
</div>
</>
)
You can use ternary operators there to render based on a condition, like this:
import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url = router.asPath;
return (
<>
<div>
{url === "something" ? <Foo /> : <Bar />}
</div>
</>
)
}
import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url = router.asPath;
return (
<>
<div>
{url === "smth" ? <First /> : <Second />}
</div>
</>
)
}
return (
<>
<div>
{url === "smth" && <First />}
{url === "smth" && <Second />}
</div>
</>
)
}
You use both methods

how to change child component state in reactjs

I came across the following problem: I need to use another component's function inside a component:
header.js
export default function Header() {
const [showModalLogin ,setShowModalLogin] = useState(false);
return(
<>
<span>Hi, <Link onClick={() =>{ setShowModalLogin(true)}}>login</Link> </span>
{showModalLogin ? <LoginModal setShowModalLogin={setShowModalLogin}/> : ''}
</>
);
}
home.js
import Header from '../../components/header/header';
export default function Home() {
return (
<>
<Header />
<Link onClick={() =>{ setShowModalLogin(true)}}>open login</Link>
</>
}
How do I do in home.js to call the setShowModalLogin function that is in header.js ? I'm trying to use the context api too, but I still can't solve it.
You can just place useState in Header component and pass setShowModalLogin as props:
import Header from '../../components/header/header';
export default function Home() {
const [isShowModalLogin ,setShowModalLogin] = useState(false);
return (
<>
<Header isShowModalLogin={isShowModalLogin} setShowModalLogin={setShowModalLogin} />
<Link onClick={() => setShowModalLogin(true)}>open login</Link>
</>
}
export default function Header({ isShowModalLogin, setShowModalLogin }) {
return(
<>
<span>Hi, <Link onClick={() => setShowModalLogin(true)}>login</Link> </span>
{isShowModalLogin ? <LoginModal setShowModalLogin={setShowModalLogin}/> : ''}
</>
);
}
Then you can do it in this way:
Create Context
Save useState inside
Use it everywhere you need
export const YourContext = createContext();
export const YourProvider = ({ children }) => {
const [isShowModalLogin, setShowModalLogin] = useState(false);
const value = {
isShowModalLogin,
setShowModalLogin
};
return <YourContext.Provider value={value}>{children}</YourContext.Provider>;
}
// App.js
const App = () => {
return (
<YourProvider>
<AppContent />
</YourProvider>
)
}
So now you can use it like here:
import Header from '../../components/header/header';
export default function Home() {
const { isShowModalLogin, setShowModalLogin } = useContext(YourContext);
return (
<>
<Header isShowModalLogin={isShowModalLogin} setShowModalLogin={setShowModalLogin} />
<Link onClick={() => setShowModalLogin(true)}>open login</Link>
</>
}

react-transition-group does not animate

I use React and tranct-transition-group to write carousel components
But I encountered the problem that the animation does not take effect. The code is as follows
Link https://stackblitz.com/edit/react-ts-mi8mwj?file=Carousel.tsx
Carousel.tsx
import React, { FC, Fragment, ReactNode, useMemo, useState } from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import CarouselItem, { ItemProps } from './CarouselItem';
import './Carousel.scss';
export interface Props {}
const Component: FC<Props> = (props) => {
const { children } = props;
const [curIndex, setCurIndex] = useState(1);
const length = useMemo(() => {
return Array.from(children as ReactNode[]).length;
}, [children]);
const onNext = () => {
setCurIndex((curIndex + 1 + length) % length);
};
const onPrev = () => {
setCurIndex((curIndex - 1 + length) % length);
};
return (
<Fragment>
<button onClick={onPrev}>prev</button>
<button onClick={onNext}>next</button>
<div className="g-carousel-wrapper">
<div className="g-carousel-window">
<TransitionGroup className="item">
{React.Children.map(children, (child, index) => {
const childElement = child as FC<ItemProps>;
if(child.type !== CarouselItem) throw new Error('必须是Item')
return (
<CSSTransition classNames="item" timeout={300} key={index}>
{React.cloneElement(childElement, {
index,
style: { display: curIndex !== index && 'none' },
})}
</CSSTransition>
);
})}
</TransitionGroup>
</div>
</div>
</Fragment>
);
};
type CarouselType = {
Item: FC<ItemProps>;
} & FC<Props>;
const Carousel: CarouselType = Component as CarouselType;
Carousel.Item = CarouselItem;
export default Carousel;
CarouselItem.tsx
import React, { CSSProperties, FC } from 'react';
export interface ItemProps {
index?: number;
style?: CSSProperties;
}
const carouselItem: FC<ItemProps> = (props) => {
const { children, style } = props;
return (
<div className="g-carousel-item" style={style}>
{children}
</div>
);
};
export default carouselItem;
I don't understand why not only there is no animation effect but also the className of CSSTransition does not exist, it seems that react-transition-group does not take effect thanks
I think we don't need to use the TransitionGroup component. CSSTransition itself supports a in prop, we can use this prop to control it's visibility.
So first, Add the in condition to the CSSTransition:
<CSSTransition
in={curIndex === index}
classNames="item"
timeout={300}
key={index}
>
And then, just remove the TransitionGroup:
<div className="g-carousel-wrapper">
<div className="g-carousel-window">
{React.Children.map(children, (child, index) => {
const childElement = child as FC<ItemProps>;
if (child.type !== CarouselItem) throw new Error('必须是Item');
return (
<CSSTransition
in={curIndex === index}
classNames="item"
timeout={300}
key={index}
>
{React.cloneElement(childElement, {
index,
style: { display: curIndex !== index && 'none' },
})}
</CSSTransition>
);
})}
</div>
</div>
It should be working now: https://stackblitz.com/edit/react-ts-kqed2n?file=Carousel.tsx

Hey how do I convert this JS into react?

I am quite new in react and just struggling a bit to make it work properly.
So here is a snippet from JS file and I need to convert it react.
let squares = document.getElementsByClassName("square");
for (let i = 0; i < squares.length; i++) {
squares[i].addEventListener("mouseenter", () => {
squares[i].classList.add("light");
setTimeout(function () {
squares[i].classList.remove("light");
}, 800);
});
}
In that react component I have just some divs with className="square"
export default function SomeComponent() {
return (
<div className="row ">
<div className="square"></div>
<div className="square"></div>
<div className="square"></div>
<div className="square"></div>
<div className="square"></div>
<div className="square"></div>
<div className="square"></div>
<div className="square"></div>
<div className="square"></div>
<div className="square"></div>
</div>
);
}
Create a component for each square.
Return a JSX div from it.
Create a state in that component for light (default it to false).
If light is true, add the class to the list of class names for the div (the classnames module is helpful here).
Add a onMouseOver function which sets the state of light to true.
Add a useEffect hook which depends on the value of light. Inside that hook, use setTimeout to change the state back to false after the time period.
holo, may you can check this?
and this is online demo
constructor(props) {
super(props);
this.state = {
name: 'React',
currentIndx: undefined,
doms: Array.from({length: 10}).fill(1)
};
}
handleMouse = (index: number) => {
this.setState({
currentIndx: index
});
setTimeout(() => {
this.setState({
currentIndx: undefined
})
}, 1000)
}
render() {
const { doms, currentIndx } = this.state;
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
<div>
{doms.map((item, index) => (<div onMouseEnter={() => this.handleMouse(index)} className={`square ${currentIndx === index ? 'light': ''}`} key={index}>{index}</div>))}
</div>
</div>
);
}
The easiest way to do it would be something like this
import React, { useState } from "react";
const ListItem = () => {
const [hovered, setHovered] = useState(false);
return (
<div
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
className={`square ${hovered ? 'light' : ''}`}
/>
);
}
const List = () => {
return (
<div className="row">
<ListItem />
<ListItem />
<ListItem />
<ListItem />
<ListItem />
<ListItem />
<ListItem />
<ListItem />
<ListItem />
<ListItem />
</div>
);
}
Create a Square component first;
import React, { useState } from "react";
import "./Square.css";
export const Square = () => {
const [light, setLight] = useState(false);
const mouseOver = () => {
setLight(!light);
};
return (
<div onMouseOver={mouseOver} className={light ? "light" : null}>
Square
</div>
);
};
export default Square;
Then on your page; import it and use it
import React from 'react'
import './App.css'
import Square from './components/Square'
function App() {
return (
<div className="container">
{Array(3)
.fill(' ')
.map((item) => {
return (
<tr>
<td className="space">
<Square />
</td>
<td className="space">
<Square />
</td>
<td className="space">
<Square />
</td>
</tr>
)
})}
</div>
)
}
export default App
When you mouseOver to the square component it will turn on red, if u do it again, className will be null so it will change back to normal color easy tutorial for you
CSS
.space{
padding: 5px;
}
.light{
color: red
}

How can I pass a ref to HOC that uses onClickOutside('react-onclickoutside')?

I use onClickOutside('react-onclickoutside') for my HOC and I can't pass ref for this HOC, I have something like below and an error appears:
const inputRef = useRef();
....
<SomeCompontnt
inputRef={inputRef}
items={items}
onSelect={onSelect}
value={selectedItem}
/>
....
export default onClickOutside(forwardRef(
(props, inputRef) => <MyHoc inputRef={inputRef} {...props} />)
);
....
Errors
Uncaught TypeError: Cannot read property 'isReactComponent' of
undefined
at onClickOutside.render (react-onclickoutside.es.js?7e48:325)
try this:
you can see MyHoc onClick output in OnclickoutsideDemo MyHookClick console
import React from "react";
import { render } from "react-dom";
import onClickOutside from "react-onclickoutside";
class OnclickoutsideDemo extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const options = this.state.showOptions ? (
<MyHookClick
onClick={e => console.log(e)}
handleClickOutside={() => this.setState({ showOptions: false })}
/>
) : null;
return (
<div>
<span
onClick={() =>
this.setState({ showOptions: !this.state.showOptions })
}
>
Click Me
</span>
{options}
</div>
);
}
}
const MyHoc = React.forwardRef((props, ref) => (
<div ref={ref} onClick={e => props.onClick("HaHa")}>
Click Me to see HaHa in console !
</div>
));
const MyHookClick = onClickOutside(props => (
<MyHoc ref={props.inputRef} {...props} />
));
export default OnclickoutsideDemo;
render(<OnclickoutsideDemo />, document.getElementById("root"));

Categories

Resources