Hey fellow developers,
so, I'm having this issue with React, and although I think I'm getting to show the 2000 as a number and a value overall, when I write inside the comment section, the number changes to NaN. I tried using the parseInt() in order to turn the span into a number, but nothing happens... Any suggestions?
Here's the code :)
import React from "react";
import Header from "../Header";
import "./contact-form.css";
function characterCounter() {
let text = document.getElementById("message").value;
let textLength = text.length;
let counter = document.getElementById("characterCounter");
let counterNumber = parseInt(counter);
counter.textContent = counterNumber - textLength;
}
class ContactPage extends React.Component {
render() {
return (
<div>
<Header />
<h1>Contact.</h1>
<form action="" className="contact-form" id="contactForm">
<label>Your Name</label>
<input type="text" placeholder="First Name..." />
<label>Your Last Name</label>
<input type="text" placeholder="Last Name..." />
<label>Your Email</label>
<input type="text" placeholder="Email..." />
<label>Your comment</label>
<textarea
name=""
id="message"
cols="10"
rows="10"
placeholder="Hey..."
onKeyDown={characterCounter}
></textarea>
<span>
Max words <span id="characterCounter">2000</span>
</span>
<button id="buttonSubmitContact" type="submit">
Submit
</button>
</form>
</div>
);
}
}
export default ContactPage;
So... you are using React, don't you? Well I will rewrite the component to solve the issue in the React's way
const MAX_CHARS = 2000
function ContactPage() {
const [charsLeft, setCharsLeft] = useState(0);
const updateCharsCount = ({target:{value}}) => {
setCharsLeft(MAX_CHARS - value)
}
return (
<div>
<Header/>
<h1>Contact</h1>
<form action="" className="contact-form" id="contactForm">
<label>Your Name</label>
<input type="text" placeholder="First Name..."/>
<label>Your Last Name</label>
<input type="text" placeholder="Last Name..."/>
<label>Your Email</label>
<input type="text" placeholder="Email..."/>
<label>Your comment</label>
<textarea
name=""
id="message"
cols="10"
rows="10"
placeholder="Hey..."
onChange={updateCharsCount}
></textarea>
<span>Max words {charsLeft}/{MAX_CHARS}</span>
<button id="buttonSubmitContact" type="submit">
Submit
</button>
</form>
</div>
);
}
export default ContactPage;
By the way, I've used functional component instead of class component, it's the current approach