Reputation: 3
I am writing the following onclick handler:
changeDate = (e) => {
console.log("e.target: ",e.target)
console.log("e.target.value: ", e.target.value)
// this.setState({date_string : e.target.value})
}
for these list items:
let dayList = <ul></ul>
dayList = this.state.days.map( (el) =>
<li
key = {el.toString()}
onClick = {this.state.loading ? null : this.changeDate}
value={el}>{el}
</li>
)
When running my react app, I get the following output from the above console logs:
e.target: <li value="2020-01-26">2020-01-26</li>
e.target.value: 2020
Why is the logged value not the same value displayed in the list object? Various combinations of toString() etc do not appear to help.
Upvotes: 0
Views: 368
Reputation: 131
You're getting undefined because target.value is only used for form elements such as input.
One solution would be to use the innerText
property as suggested by @keikai above
See this for an insightful answer: How to get value from li tag
Upvotes: 0
Reputation: 15186
Remove the value={el}
and use innerText in the handler function
e.target.innerText
Try the in-text demo:
const App = () => {
const changeDate = e => {
console.log("e.target: ", e.target);
console.log("e.target.value: ", e.target.value);
console.log("e.target.innerText: ", e.target.innerText);
};
return (
<div className="App">
<li onClick={changeDate}>{"test"}</li>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
Upvotes: 1