Question:
Hello everyone. There are two windows. The first contains a table with users and data about them, the second is a form for adding and editing these users. I can’t think of how to put focus on the newly added element (highlight it with a frame in the table).
Window with users. Marked with a comment the place where the function responsible for highlighting the current user with styles (which was clicked) is located. I think it is necessary to transfer this functionality to the reducer so that it can be called in the second window at the moment of clicking on the button for adding a new user. I would be grateful for any help!
import React from 'react'
import FirstWindowItems from './FirstWindowItems'
import {connect, useDispatch} from "react-redux"
import {createNewUser, userInfo} from "./redux/action"
const FirstWindow = ({items}) =>{
const dispatch = useDispatch();
function getElem(i, item) {
setActive(i); // ТУТ ПРОИСХОДИТ ВЫДЕЛЕНИЯ ТЕКУЩЕЦ СТРОКИ ПО КЛИКУ. Требуется сделать такое же выделение на только что добавленный элемент.
console.log(items)
dispatch(userInfo(item)); // вызываем экшен для поиска активного элемента
}
const [active, setActive] = React.useState(null);
return(
<div className = "container">
{
items.items.map((item,i) =>{
return <FirstWindowItems
item = {item}
isActive={active===i}
onClick={()=>getElem(i,item)}
key={item.id}
></FirstWindowItems>
})
}
</div>
)
}
const mapStateToProps = state => {
console.log(state.items);
return {
items: state.items
}
}
const mapDispatchToProps = {
createNewUser:createNewUser
}
export default connect(mapStateToProps, mapDispatchToProps)(FirstWindow);
Form window for working with user data (changes, addition)
import { bool } from 'prop-types';
import React from 'react'
import {connect} from "react-redux"
import {createNewUser, deleteUser, changeInfo, userInfo} from "../components/redux/action"
class SecondWindow extends React.Component{
constructor(props){
super(props);
}
handleOptionChange = e => {
this.setState(
{
selectedOption:e.target.value
}
)
}
submitHandler = e => {
e.preventDefault();
const newUser = {
id: Date.now().toString(),
FIO: "Имя",
position:"Должность",
birthDay: "год/месяц/день",
sex: true ,
fired: false
};
console.log(this.props);
this.props.createNewUser(newUser);
this.props.userInfo(newUser);
}
changeInputHandler = ({ target: t }) => {
this.setState(state => ({
...state,
[t.name]: t.type === 'checkbox' ? t.checked : t.value,
}));
const valueForUpdate = {
id: this.props.items.activeUser.id,
box: t.name,
newValue: t.type === 'checkbox' ? t.checked : t.value
};
console.log(t.checked)
this.props.changeInfo(valueForUpdate);
}
isFormValid = () => {
const {FIO, position, birthDay, sex, fired} = this.state;
console.log(FIO && position && birthDay && sex && fired);
return FIO && position && birthDay && sex && fired
}
deleteUser = () => {
this.props.deleteUser(this.props.items.activeUser);
}
render() {
return (
<form onSubmit={this.submitHandler}>
<div className="input-group mb-3">
<input type="text" className="form-control" placeholder="ФИО"
name="FIO"
onChange={this.changeInputHandler}
value={this.props.items.activeUser.FIO}
></input>
</div>
<select className="form-select" aria-label="Default select example"
name ="position"
onChange={this.changeInputHandler}
value={this.props.items.activeUser.position}>
<option defaultValue = "Выбирите должность">Выбирите должность</option>
<option value="Старший разработчик">Старший разработчик</option>
<option value="Младший разработчик">Младший разработчик</option>
<option value="Эйчар">Эйчар</option>
<option value="Уборщик">Уборщик</option>
</select>
<div className="form-group ">
<div className="mb-3"></div>
<input className="form-control" type="date" id="example-date-input"
name ="birthDay"
onChange={this.changeInputHandler}
value={this.props.items.activeUser.birthDay}></input>
</div>
<div className="form-check">
<input className="form-check-input" type="radio" name="flexRadioDefault"
id="flexRadioDefault1"
value = {true}
name ="sex"
onChange={this.changeInputHandler}
checked={this.props.items.activeUser.sex ? true : false }
></input>
<label className="form-check-label" htmlFor="flexRadioDefault1">
М
</label>
</div>
<div className="form-check">
<input className="form-check-input" type="radio" name="flexRadioDefault"
id="flexRadioDefault1"
value = {false}
name ="sex"
onChange={this.changeInputHandler}
checked={!this.props.items.activeUser.sex ? true : false}
></input>
<label className="form-check-label" htmlFor="flexRadioDefault1">
Ж
</label>
</div>
<div className="form-check">
<input className="form-check-input" type="checkbox" id="flexCheckDefault"
name ="fired"
onChange={this.changeInputHandler}
checked={this.props.items.activeUser.fired}
></input>
<label className="form-check-label" htmlFor="flexCheckDefault">
Уволен
</label>
</div>
<button type="button" className="btn btn-success" onClick = {this.submitHandler}
disabled = {!this.isFormValid}
>Добавить нового сотрудника</button>
<button type="button" className="btn btn-danger"
onClick = {this.deleteUser}>Удалить выбранного сотрудника</button>
</form>
);
}
}
const mapStateToProps = state => {
console.log(state.items.items);
return {
items: state.items,
}
}
const mapDispatchToProps = {
createNewUser: createNewUser,
deleteUser:deleteUser,
changeInfo:changeInfo,
userInfo: userInfo
}
export default connect(mapStateToProps, mapDispatchToProps)(SecondWindow);
Director
import { object } from 'prop-types'
import {CREATE_NEW_USER, DELETE_USER, USER_INFO, CHANGE_INFO} from './types'
const initialState = {
items: [
{id:1, FIO: "Шнуров В.А", position:"Старший разработчик", birthDay: "1998-05-13", sex: true, fired: false},
{id:2, FIO: "Теркин А.А", position:"Младший разработчик", birthDay: "1972-03-14", sex: true, fired: false},
{id:3, FIO: "Смолин У.В", position:"Эйчар",birthDay: "1956-07-22", sex: true, fired: true},
{id:4, FIO: "Шарапова З.Е", position:"Уборщик",birthDay: "1923-07-22", sex: false, fired: false},
],
activeUser: {}
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case CREATE_NEW_USER:
return {...state, items: state.items.concat([action.payload])}
case DELETE_USER:
return {...state, items: state.items.filter((item)=>{
return item.id !== action.payload.id;
})
}
case USER_INFO:
return {...state, activeUser: action.payload}
case CHANGE_INFO:
return {...state, items: state.items.map((item)=>{
if(item.id === action.payload.id){
console.log(item)
// console.log(action.payload.id, item[action.payload.box], action.payload.newValue);
item[action.payload.box] = action.payload.newValue;
return item
}
else return item
})
}
default:
return state;
}
}
export {reducer}
Answer:
Something like this:
// тут твой стейт после добавления последнего элемента.
let items = [ { id:1 },{ id:2 },{ id:3 } ]
// тут ты получаешь последний добавленный элемент
let newTargetItem = items.filter( ( f,i,arr ) => f.id === arr.length )
Well, then do whatever you want with it: pass it to the function for selection, use in useEffect for selection after redrawing, delete, edit.