I did search for it but nothing seems to be working for me. Also as a newbie I could not implement given solution based on the react theorems.
I have an input field inside a styled component and when i try to enter the value in the field after a keystroke the input looses the focus.
import React, { useState } from 'react';
import styled from 'styled-components';
import Button from '../../UI/Button/Button';
import './CourseInput.css';
const CourseInput = props => {
const [enteredValue, setEnteredValue] = useState('');
const [isValid, setIsValid] = useState(true);
const goalInputChangeHandler = event => {
if (event.target.value.length > 0) {
setIsValid(true);
}
setEnteredValue(event.target.value);
};
const formSubmitHandler = event => {
event.preventDefault();
if (enteredValue.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
};
const FormControl = styled.div`
margin: 0.5rem 0;
& label {
font-weight: bold;
display: block;
margin-bottom: 0.5rem;
color: ${porps => props.invalid ? 'red ' : 'black'}
}
& input {
display: block;
width: 100%;
border: 1px solid ${props => (props.invalid ? 'red' : '#ccc')};
background:${porps => props.invalid ? '#ffd7d7' : 'transparent'}
font: inherit;
line-height: 1.5rem;
padding: 0 0.25rem;
}
& input:focus {
outline: none;
background: #fad0ec;
border-color: #8b005d;
}
`;
return (
<form onSubmit={formSubmitHandler} >
<FormControl invalid={!isValid} >
<label >Course Goal</label>
<input type='text' onChange={goalInputChangeHandler} key='GoalInput' />
</FormControl>
<Button type="submit">Add Goal</Button>
</form>
);
};
export default CourseInput;