score:3
Accepted answer
All the components has same fixed class name "input-image"
. As you are querying with class name on image click it is taking the first one and updating the image there.
I have modified your code, tried in sandbox - https://codesandbox.io/s/charming-cdn-vh5xv
I'm passing 1 extra props to InputContainer and this prop is dynamic taking the index of array. Then I'm using the in the id field of the input tag and querying using this id document.querySelector(`#${imgName}`).click();
App.js
import { useState } from "react";
import "./styles.css";
import InputContainer from "./InputContainer";
export default function App() {
const [inputArr, setInputArr] = useState([]);
const addInputContainer = () => {
setInputArr([...inputArr, ""]);
};
return (
<div className="App">
<button onClick={addInputContainer}>Add Input-Container</button>
<br />
{inputArr.map((input, index) => {
return <InputContainer key={index} imgName={`img-${index}`} />;
})}
</div>
);
}
InputContainer.jsx
import { useState } from "react";
const InputContainer = ({ imgName }) => {
const [image, setImage] = useState("");
const handleClick = () => {
document.querySelector(`#${imgName}`).click();
};
const handleInput = (e) => {
const selected = e.target.files[0];
if (!selected) return;
let reader = new FileReader();
reader.readAsDataURL(selected);
reader.onload = () => {
setImage(reader.result);
};
};
return (
<div className="input-container" onClick={handleClick}>
{image ? <img src={image} className="image" /> : "Click For input"}
<input
type="file"
onChange={handleInput}
className="input-image"
id={imgName}
style={{ display: "none" }}
/>
</div>
);
};
export default InputContainer;
Source: stackoverflow.com
Related Query
- React hook changing the state variable of wrong component when file input
- Updating the react component state when a global variable changes
- Input element's value in react component is not getting re-rendered when the state changes
- React.js when using non state variable Getting error as A component is changing an uncontrolled input of type text to be controlled
- How to allow input type=file to select the same file in react component
- React + Redux - Input onChange is very slow when typing in when the input have a value from the state
- Accessing the State of a Functional Component with React Hooks when Testing with Enzyme
- React - weird behavior when useState hook sets state for the first time vs subsequent times
- How to optimize React components with React.memo and useCallback when callbacks are changing state in the parent
- Change the state when clicking outside a component in React
- Uploading a file using only the input field - React Hook Form
- How does React State Hook gets the state variable name from the ES6 Destructuring Assignment
- Reading component state just after setting when using useState hook in react
- how to get a Component variable from another component but their both in the same file React
- React component rendering even when there is no change in the state value
- How to pass input values from a child Form component to the state of its parent component for submission with react hooks?
- Why is my hook variable in React not holding the state I set it to?
- Handle multiple react form input and update the state of the component
- The state variable returned after using useState react hook shows .map is not a function
- How to update redux state using a react variable passed up to the component from a child
- React.js component not re-rendering children when the useState hook changes state
- When accessing the current state inside a React Hook's setState() call, is the prevState variable a copy or a direct reference to the state object?
- React State only updates when setting a useless state variable along with the necessary state variable
- React Hooks: state variable having wrong value in event handlers, not able to type in input
- On React hook component unmount, unable to get updated state variable value
- How to change the state of the particular component when it is clicked, using useState in react js?
- Why does react re-render twice when using the state hook (useState)?
- React input, I defined the state into initial state but still get warning changing uncontrolled to controlled input
- Using a React hook in separate file to the component
- How to reinitialize the state with react hook when rerender the components
More Query from same tag
- How to execute python scripts from react-js?
- Different output fetching json with and without arrow function on reactjs
- React: function passed in props is undefined
- React:Unable to resolve path to module and intellisense in my own typescript react moudle does not working
- Multiple properties in ReactJS inlined styles object?
- TypeScript: Require that two arrays be the same length?
- React js pass a function this.state context
- Overlapping avatars: convert SCSS to CSS and PUG to HTML
- How to implement a React Component with sub-components and call them?
- React Router in office JS excel causes white page
- How to I retrieve value from Material UI Slider to use?
- Refresh data of react app from backend every 2 seconds
- I have 2 big components/ screens and after a link press on the element I want the whole screen to load the new components without reloading
- MaterialUI withStyles, trying drilling down to a disabled switches css override
- TODOLIST Update in REACT
- The pseudo class ":first-child" is potentially unsafe when doing server-side rendering. Try changing it to ":first-of-type"
- Issue mapping an array from api fetch call
- How to prevent infinite re-rendering with useEffect() in React
- using If/Else statement in ReactJs to return a component
- How to conditionally render an image in React?
- How to set focus on button in componentDidMount
- Uncaught Invariant Violation: traverseParentPath(...): Cannot traverse from and to the same ID, ``
- How To Hide Navbar or any others section on Scroll Down in React or JavaScript?
- React-Redux Action: 'Dispatch' is not a function
- enzyme find and select first instance of element
- Expected mock function to have been called one time, but it was called zero times. in react
- React useEffect does not fetch paramter into React useState
- ReactJS, getdata from parent of child without and envent from child
- Child component is not updating from parent state change
- Can I provide a type to a React component on forehand using a generic type?