Hey guys I'm trying to remove the border of the last item in an unordered list when the list grows to a certain size. My initial thought was something like:
document.querySelector('.employee-list-item:last-child').style.border = "none";
However, React says it can't set the style property on 'null.' Is it trying to target the element before it's been rendered? Any workarounds for this?
Here's my code:
import "../css/Employee.css";
import Avatar from "./Avatar";
import React from "react";
const Employee = (props) => {
// capitalize first letter of firstName and first letter of lastName
const name = props.name
.split(" ")
.map((i) => i[0].toUpperCase() + i.slice(1))
.join(" ");
const { title } = props;
return (
<li className="employee-list-item">
<Avatar name={props.name} />
<span className={"employee-name"}>{name}</span>
<span className={"employee-title"}>{title}</span>
</li>
);
};
export default Employee;
Create a new file called "App.css" and insert some CSS code in it:
OR
You can add CSS - Employee.css
.employee-list-item:last-child{border:none !important;}
Import the stylesheet in your application:
import './App.css';
You should put the code into a useEffect hook - that ensures it will run after React has done all its magic and the Virtual DOM has been rendered to the live DOM. The the code you already thought of should work with a tweak:
useEffect(() => {
document.querySelector('.employee-list-item:last-child')[0].style.border = "none"; // or forEach(... if you expect more than one item to match
});
One way is pass a prop (ex isLast) to Employee and style based on that.
const Employee = (props) => {
return (
<li
className="employee-list-item"
style={props.isLast ? { border: "none" } : undefined}
></li>
);
};
const List = () => {
return (
<div>
{employees.map((emp, index) => (
<Employee isLast={index === employees.length - 1} />
))}
</div>
);
};