Reputation: 21
I am currently learning React and am working on a project where I'm trying to render a custom Image component. The component is to be rendered on the left or right side of the screen alternating.
I've set up a handleSide method that just returns a flipped boolean. But I am trying to call that method and pass its return value as a prop:
handleSide:
const side = true;
const handleSide = () => {
side = !side;
return side;
};
In my render():
<Image side={handleSide} src="*not including here*">
How can I get handleSide to be called and then pass the return value in for props.side? Currently it seems to just be calling the method (I think) but not actually passing it as a prop. I also tried something like this:
<Image side={handleSide} sideBool={side} src="*not including here*>
Essentially hoping that handleSide would be called and then taking the side's new value and putting it for sideBool. But that didn't seem to work -- every render returned True rather than an alteranting True False. Thanks!
Upvotes: 2
Views: 7938
Reputation: 39250
You could do the following:
const { useState, useCallback } = React;
const Image = ({ handleSide, sideBool }) => (
<div>
side is:{String(sideBool)}
<button onClick={handleSide}>toggle side</button>
</div>
);
const App = () => {
const [side, setSide] = useState(true);
const handleSide = useCallback(
() => setSide((side) => !side),
[]
);
return <Image handleSide={handleSide} sideBool={side} />;
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1