Home > Software engineering >  element placement order in react
element placement order in react

Time:11-08

I have a CRUD, and when I click on the button to make a new post, a div is rendered with the post content. The problem is that I want to change the order of posts, actually when a new post is created it is placed below the oldest post, and I want newer posts to be rendered on top.

    function MainScreen() {
    
      const dispatch = useDispatch();
    
      const user = useSelector((state) => state.user)
    const posts = useSelector((state) => state.loadPosts)
    
      const [title, setTitle] = useState("");
      const [content, setContent] = useState("");
      const [buttonGreyOut, setButtonGreyOut] = useState("#cccccc");
    
      useEffect(() => {
        if (title && content !== "") {
          setButtonGreyOut("black");
        } else {
          setButtonGreyOut("#cccccc");
        }
      },[title, content]);
    
    
    
      const handleSubmitSendPost = (e) => {
        e.preventDefault();
        dispatch(postsSlice.actions.addPost({title, content}))
        setTitle('')
        setContent('')
      };
    
      const handleChangeTitle = (text) => {
        setTitle(text);
      };
    
      const handleChangeContent = (text) => {
        setContent(text);
      };
    
    
      const [openModal, setOpenModal] = useState();
    
      if (user === '') {
        return <Navigate to="/" />
      } else {
        return (
          <div className="containerMainScreen">
            {openModal && <Modal closeModal={setOpenModal} />}
            <div className="bar">
              <h1>Codeleap</h1>
            </div>
            <div className="boxPost">
              <h2 style={{ fontWeight: 700 }}>What's on your mind?</h2>
              <h2>Title</h2>
              <form onSubmit={handleSubmitSendPost}>
                <input
                  type="text"
                  placeholder="Hello World"
                  name="name"
                  value={title}
                  onChange={(e) => handleChangeTitle(e.target.value)}
                ></input>
                <h2>Content</h2>
                <textarea
                  placeholder="Content"
                  name="content"
                  value={content}
                  onChange={(e) => handleChangeContent(e.target.value)}
                ></textarea>
                <button
                  className="createButton"
                  type="submit"
                  style={{ backgroundColor: buttonGreyOut }}
                  disabled={!title || !content}
                >
                  CREATE
                </button>
              </form>
            </div>
      
            {posts.map((post) => (
              <div className="boxPost">
                <div className="bar">
                  <h1>{post.title}</h1>
                  <MdDeleteForever
                    className="icon"
                    onClick={() => {
                      setOpenModal(true);
                    }}
                  />
                  <FiEdit
                    style={{ color: "white", fontSize: "45px", paddingLeft: "23px" }}
                  />
                </div>
                <div id="postowner">
                    <h3>@{user}</h3>
                  <h3>25 minutes ago</h3>
                  <br></br>
                  <textarea style={{ border: "none" }}>{post.content}</textarea>
                </div>
              </div>
            ))}
          </div>
        );
      }
      
      
      }export default MainScreen;

my postslice.js:

import { createSlice } from "@reduxjs/toolkit";

const postsSlice = createSlice({
  name: "posts",
  initialState: [],
  reducers: {
    // add one post to the array.
    addPost: (state, action) => {
      state.push(action.payload); // modifies the draft state.
    },
    // replace the entire array.
    replacePosts: (state, action) => action.payload
  }
});

export default postsSlice

screenshot of the page:

https://ibb.co/52MS2P1

CodePudding user response:

Well the what your code solves is array posts has all the elements as they are and new post are added to the last of the array and old post are in the starting. So they are actually implicitly sorted by the time they are added into this array

you can try to reverse your posts array every time you render it.

for reversing you can use .reverse()

so like this posts.reverse().map....

CodePudding user response:

you should edit your redux reducer/action and place new object in the first position.

something like this:

return {...pervState, posts: [newPost, ...pervState.posts]}
  • Related