I want to display the name based on user click. when browse button will click we will show list of name and if we click the name then i want to display the name with changing the state.
here is the sample code
const TestCli = () => {
const [names, setfolderName] = React.useState([
"sonu",
"monu",
"xyz",
"abc",
"lol",
]);
const [isdiv, setisdiv] = React.useState(false);
const [Name, setName] = React.useState("My name is:");
const [isName, setisName] = React.useState(false);
const displayFolder = () => {
setisdiv(true);
};
const displayInfo = (name) => {
setisdiv(!isdiv);
setisName(true);
setName("My nameis " + name);
console.log(Name);
};
return (
<React.Fragment>
<div>My name is sonu</div>
<button class="browseBtn" onClick={displayFolder}>
Browse
</button>
{isdiv ? (
<div>
{names.map((name) => (
<React.Fragment>
<span onClick={() => displayInfo(name)}>{name}</span>
<br></br>
</React.Fragment>
))}
</div>
) : null}
{isName ? <div>{Name}</div> : null}
</React.Fragment>
);
};
ReactDOM.render(<TestCli />, document.getElementById("root"));
<div id="root" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
Here printing is successful but when I print on console, it is printing wrong. for example: when I first time clicks on any name then it is printing My name is: only. then when 2nd time clicks on any name whatever previously clicked that name is printing.
The state is not reflecting