React checkbox state management with react-bootstrap or material-ui? - javascript

I am working on a project. I would using checkboxes on a component and would like to show some products which have some features. Features will be defined by user's check. I would like to know how to manage checkbox and state infos together.
I have done this project with <List> and <ListGroup>.I listed a category list in a companent. And when I select one of them(wtih onClick) I can see products which have same CategoryId on my Json-Server.(managed by my_reducer)
I researched on internet and material-ui is more usefull at checkbox management, I think. What do you think? Should I use material-ui instead of react-bootstrap for checkbox?Using both material and bootstrap at the same project will effect my web-page's loading speed? Or does it occurs any other problems?
I'm open with any idea. You can share your idea with me or you can send me guide, docs, examples about it.
ps: Please do not add github or offical pages of checkbox usage(both react and material-ui:) Because I already know them and couldn't find answers for my questions.
Thx.

Since you do not provide any code, it is hard to see what you are trying to achieve and what does "more useful at checkbox management" mean in this context. You mention <List> and <ListGroup>, but how are you using the checkbox, or are you simulating a checkbox with actionable ListGroup items?
I do not think it is a good idea to mix two user interface libraries. You would end up with inconsistent look and feel, and there could be conflicts with styles etc. Adding a new dependency will increase the loading time based on the size of the dependency. If you like material-ui better, it would make sense to migrate the whole project use it.

Here is the code try this may be it works ...and it helps.
class ShowFeatures extends React.Component {
constructor(props) {
super(props);
this.state = {
showfchr: false
};
}
toggleChange = () => {
this.setState({
showfchr: !this.state.showfchr,
});
}
render() {
return (
<React.Fragment>
<div>
<input type="checkbox" checked={this.state.showfchr} onChange={this.toggleChange}
/>
Show Me Some Features!
</div>
{ this.state.showfchr ? (
<div> Your All Feature Will Show here</div>
):(
<div>here is defaullt</div>
)
</React.Fragment>
);
}
}

Related

Force expanded state of Material-UI Accordion

We use Accordions to display editable entities and want to lock modified entities in the expanded state.
Currently, we are forced to lift up expanded state into accordion wrapper, practically duplicating built-in functionality, to prevent controlled<->uncontrolled Accordeon component transition (which is prohibited by MUI).
Something like this:
const AccordionWrapper = ({isModified = false, ...otherProps}) => {
const [expanded, setExpanded] = useState(isModified);
return (
<Accordion
expanded={expanded}
onChange={(_, expanded) => {
setExpanded(expanded || isModified);
}}
...otherProps
/> );
}
Is there a better way to achieve it?
Alternatives we have considered:
<Accordion disabled={isModified}> + custom styles to make disabled accordion look not so disabled (grayish). This is a little daunting that there is (an unlikely) chance to lock component in a collapsed state cause we don't control it.
Send PR to allow controlled<->uncontrolled transition of expanded. In this case we could <Accorrdion expanded={isModified ? true : undefined}>. Actually, there is no strong technical problem with such transition (especially when/if https://github.com/mui-org/material-ui/pull/29237 gets merged)
Maybe add a new Accordion prop like "forceExpand" if MUI team will find it useful
PS. I hope MUI devs will see points 2 and 3 here on SO, cause these questions/suggestions probably are a non-issue and should not be in the MUI issue tracker.
If you want to add a custom expand toggle on MUI Accordion then you get the same with a property:-
defaultExpanded={Boolean}
So it will be like:-
<Accordion defaultExpanded={true}>
{...otherProps}
</Accordon>

Create a custom Show Layout component

I'm trying to create a custom layout component, so I can design my Show page better.
I'm not sure why some things work and some don't. My plan is to use the Material-UI <Grid> component. I know that the Grid component doesn't pass the props, then I'm extending to my own:
export default function OrderShow(props) {
return (
<Show {...props}>
<CustomGrid>
<TextField source="shortId" label="Short ID" />
</CustomGrid>
</Show>
);
}
My CustomGrid component, which is just a draft yet, is cloning its children to pass the props:
function CustomGrid(props) {
return React.Children.map(props.children, (child) => React.cloneElement(child, props));
}
When I use it, the TextField receives the source, and renders it correctly. However the label is gone. I'm not sure why this happens.
Another problem is that when I try to use the CustomGrid with a ReferenceField, it doesn't work at all:
<Show {...props}>
<CustomGrid>
<ReferenceField source="user" reference="users" label="Name" link="show">
<FunctionField render={(record) => `${record.firstName} ${record.lastName}`} />
</ReferenceField>
</CustomGrid>
</Show>
I can see that the props are passed until the ReferenceField, but it's lost before reaching the FunctionField:
Is there a better way to customize the SimpleShowLayout and continue using the TextField and other components from react-admin?
Yes, there is a way. Simply put react-admin's SimpleShowLayout is a little bit more coplex then just passing the props to the children fields. That's why you have to recursively iterate until you reach a field and perform the stuff the react-admin does.
Finally I have decided to share some privately developed components in a new package I am building. I have added layouts which work both with Box and Grid material-ui's components. You can have a look here: ra-compact-ui

Storage-design for fetched data (globally?) & navigation

im new to JavaScript & React (and new to stackoverflow too) and I hope to get some ideas/ answers regarding the "logic" in implementing data-storage. I have/ had a dev-background in Obj-C / iOS few years back. So some general concepts in web-dev might not be familiar to me.
Hope I'm doing everything correct in my first post, never really used stackoverflow so far :)
So, basically I have a small project with a Sider und Content (using Ant Design Framework). In this project, im trying to figure out, how generell stuff has to be done, like Navigation through the views, data handling and so on.
In one Tab in the SideBar, i'm using a Table (also antd). If you press on one Item, it should show a detail-View with the props of that specific item (later it should be the form for data change/input).
My App.js:
<Content style=...>
<Switch>
<Route exact path="/tasks" >
<TasksTable
data={this.state.tasksData}
handleOnRowClicked = {this.handleOnRowClicked}
/>
</Route>
<Route exact path="/details">
<TasksDetail currentTask= {this.state.currentDetailTask}/>
</Route>
....
</Switch>
</Content>
In the TasksTable-Component:
...
const history = useHistory()
...
function handleOnRowClicked(record, rowIndex,event) {
console.log("Clicked on cell", event)
history.push("/details/")
props.handleOnRowClicked(record.id)
}
return(
<Table
dataSource={props.data}
onRow={ (record, rowIndex) => {
return {
onClick: event => {
handleOnRowClicked(record, rowIndex,event) }
}
}
}
>
<Column title="Name" dataIndex="name" key="name" />
<Column title="Kunde" dataIndex="client_name" key="client_name" />
<Column title="Fertigstellung bis" dataIndex="completion_date" key="completion_date" />
<Column title="HinzugefĆ¼gt" dataIndex="created" key="created" />
<Column title=""
dataIndex="remove_button"
key="remove_button"
render={removeButton => {
return <button key="ButtonKey" onClick={event => handleOnButtonClicked(event)}>Remove</button>
}}/>
</Table>
)
}
What i want to achive:
When clicked on one row of the table, i want to push another "view"/ Side to show details of selected row. Currently I'm doing this in the TasksTable-Component with history.push(). I'm wondering if this is the correct way of showing (detail-)views? Because I need to call props.myHandleCallbackFunc(selectedItem) in App.js to set a State names "currentlySelected" for then passing this state as prop to the pushed detail view.
Hope you get my point.
As far as I understood, I should use ... for automating the navigation-process. Problem is: As I use the Table from antdesign, I need to make this programatically. Thats why I have this workaround (at least it feels like one) with the onRow property... Is this the correct way of using the table? I have the feeling its not.
Problem with my workaround: I've rendered a Button into the Cells to deliver a delete-Button.
Problem there: Even if i click on the Button, it is registered as a click on the row and therefor pushes my detailview... I tried to differentiate with event.target.key but had no success.
Is it the right way of holding all data fetched by my api in the uppermost component and share it to sup-components via props? How can I update it from subcomponents then? Should every Subcomponent should get a handler via props to call back, when value changed?
Or in other words: Make the http-request from the sub-comp or send the changed data to the App-component and let it then trigger the HTTP-POST-request? I strongly guess its second choice.
Thank you so much, I appreciate every answer. Im trying to get things working since few hours now...
(Sorry for spelling mistakes, english is not my native one).
P.S: Actually I wanted to post this yesterday but took few extra hours for working through the "similar questions"... Still, open questions :D
Robin
Redux is a predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.
You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.
https://redux.js.org/introduction/getting-started

How to access and use a value from a child component on redux-form to make a checkbox work and enable conditionally rendered extra options

I'm using redux-form. I need to conditionally render extra options on user click of a checkbox in a child component.
I am able to do this on the parent file (in the SOW Type section of the form) using 'formValueSelector' (see sandbox: https://codesandbox.io/s/currying-cloud-isu8c) but on the third option in this section ('Custom Professional Services SOW') on clicking the checkbox I need to further condionally render some options on clicking the new checkbox that is exposed inside ('Customised Professional Services').
The file containing the code for the child component is 'CustomProfExtOptions'. What code do I need in this child component and/or the parent component in order to get this nested checkbox to work/enable conditional rendering on checking the box
I understand I need to access the value of the field in this child component on the form in order to manipulate it's state (mapStateToProps?) and allow the conditional rendering to work. I have done this successfully in the parent (as the sandbox shows) but I don't know how to get his working in the child component.
I have googled extensively on this for three days and tried to tweak other examples I have found to fit this specific problem (the greyed out text at the bottom of 'CustomProfExtOptions.js' where the child component code is held) but I've yet to find anything that works.
What is working so far:
The 'formValueSelector' code (as per the Redux-Form docs which allows access the values in the fields of the form) I am using in the parent container for the form (a file called 'PdfGenFormContainerRedux.js') is as follows:
PdfGenFormContainerRedux = reduxForm({
form: "StatementOfWorkApplication"
})(PdfGenFormContainerRedux);
const selector = formValueSelector("StatementOfWorkApplication");
PdfGenFormContainerRedux = connect((state) => {
const hasProductSowValue = selector(state, "productSOW");
const hasTeradataExtOptionsValue = selector(state, "teradata");
const hasCustomProfExtOptions = selector(state, "customExtOptions"); //selector created
return {
hasProductSowValue,
hasTeradataExtOptionsValue,
hasCustomProfExtOptions
};
})(PdfGenFormContainerRedux);
export default PdfGenFormContainerRedux;
This allows me to conditionally render the second hidden field on the click of the checkbox by using a variable called props.hasCustomProfExtOptions as demonstrated below:
<div className="checkbox-group">
<div>
<label className="checkbox-group">
<Field
name="customExtOptions"
className="form-checkbox"
component="input"
type="checkbox"
/>
Custom Professional Services SOW
{props.hasCustomProfExtOptions && ( //conditional rendering bit here
<div>
<Field
name="custProfServices"
type="input"
component={CustomProfExtOptions}
label="Custom Options Info"
placeholder="Location"
formId={formId}
/* hasProfServ={props.hasProfServ} */
/>
</div>
)}
</label>
</div>
</div>
</div>
This works fine on the parent container but how do I get it working on the checkbox labelled 'Customised Professional Services' in the child component? (the file called 'CustomProfExtOptions')
Just to add, i need any input from this nested section to be included in the final submission of the form.
Any help would be greatly appreciated

how to access value of state of Root Component in the child component

I have created a React application. In this application, I've created following components:
App Component (root) : where data is loaded into state
CardList Component: List of Cards, data is passed to it using props
Card Component: use forEach to pass data to Card and it has button
CustomButton Component: acts like a button with style
What I want is when the user clicks button on any of the Card, a number should get increased everytime. But I am not able to access Data here.
Can anyone help?
Here is the Card Component for your reference:
class Card extends Component {
render() {
return (
<div className="tc bg-light-green dib br3 pa3 ma2 grow bw2 shadow-5">
<h2>Votes: {this.props.votes}</h2>
<div>
<img src={this.props.pic} alt='Superstar'/>
<div>
<h2>{this.props.name}</h2>
<p>{this.props.email}</p>
</div>
</div>
<ActionButton btnText="Vote Now!" clickhandler={this.onVoteButtonClick}/>
</div>
);
}
onVoteButtonClick = (event) => {
console.log('It was clicked : '+this.props.id);
}
}
Two options which you should research more to see what suits your need best:
Redux (or something similar)
The new Context API available in React 16.
The gist of either solution is that you're managing application state independently of the dependent component tree(s). The Context API is arguably easier to implement whereas you'll currently find many more examples explaining the Redux approach as it's still the most common solution right now.

Categories

Resources