score:1
Here is a simple app just in one file :) You can read the comments and try to understand what is going on. It will give you an idea of how you can keep a status
state in your store, dispatch an action and update your state.
As you will see, Post
and List
components does not have any state. They are just dumb components. The parent one, Posts
component renders them.
You can see a working example here, fork and play it. There are separate directories and files for this example. I just put everything in one file to move it here properly. I can't promise to keep the sandbox too long, so you may want to fork it immediately :)
PS: This is a midnight fun. It may include not the best practices :)
import React from "react";
import ReactDOM from "react-dom";
import { Provider, connect } from "react-redux";
import { createStore, combineReducers } from "redux";
// To use styles in a single file. You can use a .css file to define those
// and use className instead of styles in the Post component
const styles = {
post: { border: "1px solid gray", marginTop: "-1px" },
show: { backgroundColor: "silver"},
}
// Posts is the parent component. It renders Post and List component by
// mapping the posts.
class Posts extends React.Component {
// This method changes the status state by passing a post to
// the action creator
handleStatus = post => this.props.changeStatus(post);
// This method maps the posts and renders Post components for each post.
// We are passing the post and isActive boolean.
getPosts() {
return this.props.posts.map(post => {
// We are getting the isActive by checking the status state
// if it has our post's id.
const isActive = this.props.status[post.id];
return <Post key={post.id} post={post} isActive={isActive} />;
});
}
// This method renders our List items, li's. Again, we are passing the
// post and our handleStatus method to change the status.
getList() {
return this.props.posts.map(post => (
<List key={post.id} post={post} handleStatus={this.handleStatus} />
));
}
render() {
return (
<div>
{this.getPosts()}
<ul>{this.getList()}</ul>
</div>
);
}
}
// Post is a stateless, dumb component. It just renders the post item.
const Post = props => {
const { id, title } = props.post;
const { isActive } = props;
// We check the isActive and if it is true then add a show class.
let classes = styles.post;
if (isActive) {
classes = { ...classes, ...styles.show };
}
return (
<div style={classes}>
<p>ID: {id} </p>
<p>Title: {title}</p>
</div>
);
};
// List is a stateless, dumb component just renders li's. But, it has
// handleStatus prop. By onClick and using another method, we are
// passing our post back to the parent, to the handleStatus method
const List = props => {
const { post, handleStatus } = props;
const changeStatus = () => handleStatus(post);
return <li onClick={changeStatus}>{post.title}</li>;
};
// We open our state to our component.
const mapStateToProps = state => ({
posts: state.posts.posts,
status: state.posts.status,
});
// This is our action creator, takes the post as parameter and
// use it as the payload.
const changeStatus = post => ({
type: types.CHANGE_STATUS,
post,
});
// Connecting our component.
const ConnectedPosts = connect(
mapStateToProps,
{ changeStatus },
)(Posts);
// Just defining our action creator types, avoiding magic strings.
const types = {
CHANGE_STATUS: "CHANGE_STATUS",
};
// This is our reducer. We have one posts property and one status in our state.
const initialState = {
posts: [
{ id: "1", title: "foo" },
{ id: "2", title: "bar" },
{ id: "3", title: "baz" },
],
status: {},
};
// Our reducer takes the post and adds post's id in our status state.
// In the initial state they are all undefined, so not true. In the first
// click, we change to true for each post. If we click again, we change it to
// false without mutating our original state.
const posts = (state = initialState, action) => {
switch (action.type) {
case types.CHANGE_STATUS: {
const {
post: { id },
} = action;
const newStatus = { ...state.status, [id]: !state.status[id] };
return { ...state, status: newStatus };
}
default:
return state;
}
};
// Our store.
const rootReducer = combineReducers({
posts,
});
const store = createStore(rootReducer);
// Rendering our app.
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<ConnectedPosts />
</Provider>,
rootElement,
);
score:1
You can just store selectedID (or index) and use simple condition, sth like this:
class Posts extends Component {
render() {
return (
<div>
{this.props.posts.map((post, index) =>
<Post isActive={this.props.selectedIDX === index} post={post} />
)}
</div>
);
}
}
// connect with posts and selectedIDX
class List extends Component {
constructor (props) {
super(props)
this.onClickHandler = this.onClickHandler.bind(this);
}
onClickHandler = (id) => {
this.props.actionToSetSelectedIDX( id );
}
render() {
return (
<ul>
{this.props.posts.map((post, index) =>
<li onClick={(e, index) => this.onClickHandler(index) }>{post.name}</li>
)}
</ul>
);
}
// connect with posts, selectedIDX and actionToSetSelectedIDX
Source: stackoverflow.com
Related Query
- Can I change state in 100 components in one click?
- React - change state of one button from 100 buttons array, and reset state of all buttons on one click
- Can we pass setState as props from one component to other and change parent state from child component in React?
- How to change state in one page from a link click from another page?
- How can click on button to get one of components with react
- How can I select a state property object name dinamically to change one of its properties(childs?) on react?
- React- How can I change the state when I click on a different page?
- How can I change state of one element without affecting others with the same state?
- How can I change parent state in two children components using Hooks in React?
- Can I change one component State from another component?
- Can I have one onClick function to change different state values in React-js
- How can I change the state of one React component based on the value of its sibling?
- Can you pass down state to child components with React Hooks?
- Can I manually trigger a state change when testing using react-testing-library?
- can we attach click handlers to custom child components
- How can I share state data between components using custom hooks?
- useState hook can only set one object at the time and return the other object of the same array to initial state
- Change component state on button click
- In React componentDidUpdate, can props and state change at the same time?
- Map of React Components not re rendering on State Change
- ReactJS onClick state change one step behind
- Change state on click then change again after delay and show message in React
- React Native ListView not re-rendering on state change by click
- Why can components only return one node in ReactJS? (Is there a fundamental reason?)
- Using onClick function on a styled-components button doesn't change state until the second click (added sandbox URL)
- React - change css style in one specific state
- Can one control the state of Antd Table's "Check All" control?
- React Hooks, Conditionally change state inside onClick function, updates on the next click
- react stateless child components do not update on state change in parent component
- React Click Counter: Updating State of just one element
More Query from same tag
- importing custom npm package results in empty/null object
- I'm at a loss: Line 35:9: Parsing error: Expected corresponding JSX closing tag for <Switch>
- How to validate a field onBlur and other field onChange using Formik?
- How to Dynamically change the friendly name in Twilio Flex Webchat
- How to override material ui shadows in the theme
- Show a React Skeleton Loader until a image load completely
- What is the significance of keys in ReactJS?
- PrismJS with React : using babel-plugin-prismjs
- react-router mounts the wrong component
- How does relay or Apollo-react solve mutations that involve multiple relationships
- Global variable not defined across multiple useEffects
- How to target props in Class Component
- Compound Component for Storybook Reactjs
- Images not showing up in react
- How to make the color of a div change permanently after it has been clicked in react.js
- Anchor <a> tags not loading components instantly in Chrome when using #
- React + Three.js canvas does not resize correctly when making the browser window smaller
- knex issue whereNotExists
- Animate does not work with whileHover in React
- React - Error: Maximum update depth exceeded - useReducer
- Child component's props not updating when state changes
- how to uniquely identify tags in react
- React useReducer and context: how to provide state selectors?
- alternative for this componentWillMount case?
- What would be the best way filtering the huge data using Javascript/react/redux
- XMasonry, XBlock (react-xmasonry) using as separate components: TypeError: this.props.parent is undefined
- React useState working other then expected
- How do I query for gatsby-image?
- Material-UI - why different css is shown on prod environment then development env
- How to trigger a graphql query (via useQuery or useLazyQuery ) when the user types text into a input text field