Passing Style From Component State in ReactJS - javascript

I have the following component:
import React from "react";
import { connect } from "react-redux";
class Filter extends React.Component {
state = {
value: ''
};
handleChange = (e) => {
let value = e.target.value;
if(value){
document.getElementById("clear").style["display"] = "none";
document.getElementById("fetch").style["display"] = "none";
} else {
document.getElementById("clear").style["display"] = "inline-block";
document.getElementById("fetch").style["display"] = "inline-block";
}
this.setState({ value });
this.props.handleFilter({ value });
}
render(){
let content = this.props.items > 0 ? (
<div
className="filter"
>
<input
id="search-input"
type="text"
placeholder="Search..."
value={this.state.value}
onChange={this.handleChange}
/>
</div>
) : <div></div>
return content;
}
}
const mapStateToProps = (state,props) => ({
items: state.settings.length
});
module.exports = connect(mapStateToProps, null)(Filter);
Is there a way I can more gracefully pass props to the clear and fetch components? I'm trying to style them based on interactions with my search input (basically, I'd like to be able to style them whenever my search value is at ""). How do I send down styles as a prop based on the state of my current component?

Please react-jss that is exactly what you are searching for: please find the sample below:
import React, {
Component
} from 'react'
import injectSheet from 'react-jss'
import classNames from 'classnames'
class someComponent extends Component {
handleClose = () => {}
render() {
const {
classes,
} = this.props
return ( <
div className = {
classes.resize
} >
<
/div>
)
}
}
const styles = {
container: {
width: '100%',
height: '100rem'
borderBottom: '10px'
}
}
export default injectSheet(styles)(someComponent)

If you use a library called styled-components, you can easily do this like in this example: https://www.styled-components.com/docs/basics#passed-props. The idea with that lib is that you wrap your basic HTML components, like <input> to <Input>, then use the new <Input> component in your render() method. The new component will be controlled by passing values from your state as a prop.

Related

Lazy load a React component from an array of objects

I have made for me a Tutorial-Project where I collect various React-Examples from easy to difficult. There is a "switch/case" conditional rendering in App.js, where I - depending on the ListBox ItemIndex - load and execute the selected Component.
I am trying to optimize my React code by removing the "switch/case" function and replacing it with a two dimensional array, where the 1st column contains the Component-Name 2nd column the Object. Further I would like to lazy-load the selected components.
Everything seems to work fine, I can also catch the mouse events and also the re-rendering begins but the screen becomes white... no component rendering.
App.js
import SampleList, { sampleArray } from './SampleList';
class App extends React.Component {
constructor(props) {
super(props);
this.selectedIndex = -1;
}
renderSample(index) {
if((index >= 0) && (index < sampleArray.length)) {
return React.createElement(sampleArray[index][1])
} else {
return <h3>Select a Sample</h3>;
}
}
render() {
return (
<header>
<h1>React Tutorial</h1>
<SampleList myClickEvent={ this.ClickEvent.bind(this) }/>
<p />
<div>
<Suspense> /**** HERE WAS MY ISSUE ****/
{ this.renderSample(this.selectedIndex) }
</Suspense>
</div>
</header>
);
}
ClickEvent(index) {
this.selectedIndex = index;
this.forceUpdate();
}
}
SampleList.js
import React from 'react';
const SimpleComponent = React.lazy(() => import('./lessons/SimpleComponent'));
const IntervalTimerFunction = React.lazy(() => import('./lessons/IntervalTimerFunction'));
const sampleArray = [
["Simple Component", SimpleComponent],
["Interval Timer Function", IntervalTimerFunction]
];
class SampleList extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
this.selectOptions = sampleArray.map((Sample, Index) =>
<option>{ Sample[0] }</option>
);
}
render() {
return (
<select ref={this.myRef} Size="8" onClick={this.selectEvent.bind(this)}>
{ this.selectOptions }
</select>
);
}
selectEvent() {
this.props.myClickEvent(this.myRef.current.selectedIndex);
}
}
export default SampleList;
export { sampleArray };
You have several issues in that code:
If you use React.lazy to import components dynamically, use Suspense to show a fallback;
The select can listen to the change event, and receive the value of the selected option, that is convenient to pass the index in your case;
Changing a ref with a new index doesn't trigger a re-render of your components tree, you need to perform a setState with the selected index;
I suggest you to switch to hooks, to have some code optimizations;
Code:
import React, { Suspense, useState, useMemo } from 'react';
const SimpleComponent = React.lazy(() => import('./lessons/SimpleComponent'));
const IntervalTimerFunction = React.lazy(() =>
import('./lessons/IntervalTimerFunction'));
const sampleArray = [
['Simple Component', SimpleComponent],
['Interval Timer Function', IntervalTimerFunction],
];
export default function App() {
const [idx, setIdx] = useState(0);
const SelectedSample = useMemo(() => sampleArray[idx][1], [idx]);
const handleSelect = (idx) => setIdx(idx);
return (
<Suspense fallback={() => <>Loading...</>}>
<SampleList handleSelect={handleSelect} />
<SelectedSample />
</Suspense>
);
}
class SampleList extends React.Component {
constructor(props) {
super(props);
}
selectEvent(e) {
this.props.handleSelect(e.target.value);
}
render() {
return (
<select ref={this.myRef} Size="8" onChange={this.selectEvent.bind(this)}>
{sampleArray.map((sample, idx) => (
<option value={idx}>{sample[0]}</option>
))}
</select>
);
}
}
Working example HERE

How to pass state to defaultValue of select form in react js

I need to pass state to defaultValue props in select form. I'm using Ant.design to create form elements. When i pass state to defaultValue props directly, the value state will return undefined. So, i create getDefaultSOFValue() to retrieve value from request and pass it to state. Here my components code:
SelectInput.js
import React from 'react'
import { Select } from 'antd'
import './SelectInput.css'
function SelectInput(props) {
return(
<Select defaultValue={props.defaultValue} value={props.value} onChange={props.onChange} placeholder={props.placeholderSelect} style={props.styleSelect}>
{props.valueSelect}
</Select>
)
}
export default SelectInput
Form.js
import SelectInput from '../../../components/Form/Select/OrdinarySelect/SelectInput'
import { Select } from 'antd'
import 'antd/dist/antd.css'
import axios from 'axios'
class Form extends Component {
constructor(props) {
super(props)
this.getAccountName = this.getAccountName.bind(this)
this.getDefaultSOFValue = this.getDefaultSOFValue.bind(this)
this.handleSOFChange = this.handleSOFChange.bind(this)
this.state = {
inputSOF: '',
inputSOFDefaultValue: [],
valueSOF: ''
}
}
componentDidMount(){
// Fetch formInputData API
let formInputDataUrl = 'https://localhost:8000/formInputData'
let data = {
'inputPage': 'testInput'
}
axios.post(formInputDataUrl, data)
.then(res => {
// Assign "sof account" object to new Array.
let copyOfSoffAll = {
0: res.data.sofManagamentServiceResponse.sofAll.ccaccountList[1],
1: res.data.sofManagamentServiceResponse.sofAll.caaccountList[0],
2: res.data.sofManagamentServiceResponse.sofAll.caaccountList[1],
3: res.data.sofManagamentServiceResponse.sofAll.saaccountList[3]
}
this.setState({
inputSOFDefaultValue: res.data.sofManagamentServiceResponse.sofAll.ccaccountList[1],
inputSOF: copyOfSoffAll,
})
})
.catch(err => console.log(err))
}
getDefaultSOFValue(){
// this function used for get defaultValue and pass it to defaultValue prop in Select
}
getAccountName(){
return Object.values(this.state.inputSOF).map((value, index) => {
return <Option key={index} value={ value.accountBalance } >{ value.accountName } <br /> { value.accountNumber }</Option>
})
}
handleSOFChange(value){
this.setState({
valueSOF: value
})
}
render(){
return(
<div style={{ width: '100%' }}>
<div className='container'>
<SelectInput
defaultValue={ this.getDefaultSOFValue() }
valueSelect={ this.getAccountName() }
styleSelect={{ width: '60%' }}
onChange={this.handleSOFChange}
/>
</div>
</div>
)
}
}
export default Form

useState to update an object property

I am new to React. I have a functional component that is used to render am image and some properties of an image passed as props to the component. I would like to update the image source when there is an error rendering the image. I would also like to update the state property of the parent component and pass it back to the parent. I am not sure how to achieve the same. I have been struggling for so long to achieve this. Please can someone help me solve this issue. Many thanks in advance.
Parent Component:
import React, {
useState
} from 'react';
import PropTypes from 'prop-types';
import ImageRenderer from './ImageRenderer';
import VideoRenderer from './VideoRenderer';
const getComponent = {
'image': ImageRenderer,
'video': VideoRenderer
}
const AssetRenderer = (props) => {
console.log('props in asset ren:', props);
const [assetInfo, setAssetInfo] = useState(props);
console.log('assetInfo in parent:', assetInfo);
const isPublished = assetInfo.assetInfo.isAssetPublished;
let source = assetInfo.assetInfo.assetUrl;
const PreviewComponent = getComponent[assetInfo.assetInfo.type];
return ( < div > {
isPublished && source && < PreviewComponent assetInfo = {assetInfo} setAssetInfo = { setAssetInfo } />} </div>
);
}
AssetRenderer.propTypes = {
assetInfo: PropTypes.object.isRequired
};
export default AssetRenderer;
Child Component:
import React from 'react';
import PropTypes from 'prop-types';
import {
Subheading
} from '#contentful/forma-36-react-components';
const ImageRenderer = props => {
console.log('inside image renderer', props);
return ( <
div id = "asset-img" >
<
Subheading > Image preview: < /Subheading> <
p > Name: {
props.assetInfo.assetInfo.name
} < /p> <
p > Type: {
props.assetInfo.assetInfo.type
} < /p> <
p > Url: {
props.assetInfo.assetUrl
} < /p> <
img src = {
props.assetInfo.assetInfo.assetUrl
}
alt = "name"
onError = {
e => {
props.setAssetInfo(assetInfo => {
return { ...props.assetInfo.assetInfo,
assetUrl: 'https://example.com/404-placeholder.jpg',
isAssetPublished: false
} //would like to update the asset url to 404 and also set isAssetPublished to false and pass it back to parent to update parent state
});
}
}
/> <
/div>
)
}
ImageRenderer.propTypes = {
assetInfo: PropTypes.object.isRequired
};
export default ImageRenderer;
Instead of using new state in ImageRenderer component, you can just pass setState of Parent via props like this;
parent component
import React, { useStae } from 'react'
const parentCompoennt = props => {
const [assetInfo,setAssetInfo] = useState();
return (
<ImageRenderer assetInfo={assetInfo} setAssetInfo={setAssetInfo} />
);
}
imageRenderer component
const ImageRenderer = props => {
return(
<div id="asset-img">
<p> Name: {props.assetInfo.assetInfo.name} </p>
<p> Type: {props.assetInfo.assetInfo.type} </p>
<p> Url: {props.assetInfo.assetInfo.assetUrl} </p>
<img src={props.assetInfo.assetInfo.assetUrl} alt="name" onError={e => {
props.setAssetInfo(assetInfo => {
return { ...props.assetInfo, assetUrl: 'https://example.com/404-placeholder.jpg' } //would like to update the asset url to 404 and also set isAssetPublished to false and pass it back to parent to update parent state
});
}}/>
</div>
)
}
If the purpose is to handle image error only, then you can achieve it without re-rendering a component:
<img src={assetInfo.assetInfo.assetUrl} alt="name"
onError={e => {
e.target.src = 'https://example.com/404-placeholder.jpg';
}}
/>

React JS - How to access props in a child component which is passed from a parent component

In my react application, I am passing my data from parent to child as props. In my child component, I am able to see the data in props however when I try to access the data, I am getting an error saying "cannot read property of undefined".
I have written my child component like below-
Child Component-
import React from 'react';
import ReactDOM from 'react-dom';
import { setData } from '../actions/action'
import { connect } from 'react-redux'
import {
Accordion,
AccordionItem,
AccordionItemTitle,
AccordionItemBody,
} from 'react-accessible-accordion';
import 'react-accessible-accordion/dist/fancy-example.css';
import 'react-accessible-accordion/dist/minimal-example.css';
const ChildAccordion = (props) => {
console.log(props);
return (
<Accordion>
<AccordionItem>
<AccordionItemTitle>
<h3> Details:
{ props?
props.map(d =>{
return <span>{d.key}</span>
})
:
""
}
</h3>
<div>With a bit of description</div>
</AccordionItemTitle>
<AccordionItemBody>
<p>Body content</p>
</AccordionItemBody>
</AccordionItem>
</Accordion>
)
};
export default ChildAccordion
Parent Component-
import React from 'react';
import ReactDOM from 'react-dom';
import ChildAccordion from './ChildAccordion'
import { setData } from '../actions/action'
import { connect } from 'react-redux'
import {
Accordion,
AccordionItem,
AccordionItemTitle,
AccordionItemBody,
} from 'react-accessible-accordion';
import 'react-accessible-accordion/dist/fancy-example.css';
import 'react-accessible-accordion/dist/minimal-example.css';
class ParentAccordion extends React.Component {
componentWillMount() {
//call to action
this.props.setData();
}
getMappedData = (dataProp) =>{
if (dataProp) {
let Data = this.props.dataProp.map(d =>{
console.log(d);
})
}
}
render(){
const { dataProp } = this.props;
return (
// RENDER THE COMPONENT
<Accordion>
<AccordionItem>
<AccordionItemTitle>
<h3>Policy Owner Details:
{ dataProp?
dataProp.map(d =>{
return <span>{d.key1}</span>
})
:
""
}
</h3>
</AccordionItemTitle>
<AccordionItemBody>
<ChildAccordion {...dataProp} />
</AccordionItemBody>
</AccordionItem>
</Accordion>
);
}
}
const mapStateToProps = state => {
return {
dataProp: state.dataProp
}
};
const mapDispatchToProps = dispatch => ({
setData(data) {
dispatch(setData(data));
}
})
export default connect (mapStateToProps,mapDispatchToProps) (ParentAccordion)
I am using map function inside as my api response can be array of multiple objects.
Once you know what the prop that you're passing in is called, you can access it like so from within your child component: {props.data.map(item => <span>{item.something}</span>}
const Parent = () => {
return (
<Child data={[{ id: 1, name: 'Jim' }, { id: 2, name: 'Jane ' }]} />
);
}
const Child = (props) => {
return (
<ul>
{props.data.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
);
}
You are passing dataProp down to ChilAccordian as a prop. So in Child component you should access it using props.dataProp and do map on props.dataProp but not on props directly
ChildAccordian:
<h3> Details:
{ Array.isArray(props.dataProp) && props.dataProp.length > 0 ?
props.dataProp.map(d =>{
return <span key={d.id}>{d.key}</span>
})
:
""
}
</h3>
Also keep in mind that you have to add unique key to parent Jsx element when you generate them in loop like for loop, .map, .forEach, Object.keys, OBject.entries, Object.values etc like I did in the above example. If you don’t get unique id from the data then consider adding index as unique like
<h3> Details:
{ Array.isArray(props.dataProp) && props.dataProp.length > 0 ?
props.dataProp.map((d, index) =>{
return <span key={"Key-"+index}>{d.key}</span>
})
:
""
}
</h3>
Edit: If it is an object then do something like below and regarding using a method to generate jsx elements
getMappedData = dataProp =>{
if(props.dataProp){
Object.keys(props.dataProp).map(key =>{
return <span key={"Key-"+key}>{props.dataProp[key]}</span>
});
}else{
return "";
}
}
<h3> Details:
{this.getMappedData(props.dataProp)}
</h3>

Clear input in stateless React component

I want to implement an X icon inside Input component that will clear the input field. I can easily do it if I control the state. But is it actually possible with stateless component?
I use react-semantic-ui, their stateful components have auto controlled state.
So I want to create an input that can be used like this:
//Controlled
class App extends React.Component {
state = {
value:''
}
onChange = (event, props) => {
this.setState({value: props.value});
}
onClearInput = () => {
this.setState({value: ''});
}
render() {
return (
<MyInput
clearable
value={this.state.value}
onChange={this.onChange}
onClearInput={this.onClearInput}
/>
)
}
}
Or
// Uncontrolled
class App extends React.Component {
onChange = (event, props) => {
doSomething(props.value);
}
render() {
return (
<MyInput
clearable
onChange={this.onChange}
/>
)
}
}
In the second example, clearable feature will not work because we're not controlling the value.
MyInput can be implemented like this:
import React from 'react';
import { Input } from 'semantic-ui-react';
import ClearIcon from './ClearIcon';
function MyInput(props) {
const prepareProps = {...props};
if (props.clearable) {
prepareProps.icon=<ClearIcon onClick={props.onClearInput} />;
delete prepareProps.clearable;
}
delete prepareProps.onClearInput;
return (
<div className="my-input">
<Input {...prepareProps} />
</div>
);
}
...etc.
My problems:
clearable feature must work in both controlled and uncontrolled manner.
clearable feature should not require a handler. It would be nice to just provide a prop and handle the render and behavior of the X button under the hood.
I don't see any way to make this work. Any ideas?
Allowing the user of your component to set the value via props and still being able to clear the input can be easily achieved, e.g. like this:
class MyInput extends React.Component {
constructor(props) {
super(props);
this.state = {value: props.value || ''};
}
handleChange = event => {
const { onChange } = this.props;
this.setState({ value: event.currentTarget.value });
onChange && onChange(event);
};
handleClear = () => {
const { onClearInput } = this.props;
this.setState({ value: "" });
onClearInput && onClearInput();
};
render() {
const { value } = this.state;
const { clearable, onChange, ...inputProps } = this.props;
const clearIcon = clearable && <ClearIcon onClick={this.handleClear} />;
return (
<div className="my-input">
<Input value={value} icon={clearIcon} onChange={this.handleChange} {...inputProps} />
</div>
);
}
}
You could even make it more composable by using an hoc or render props as proposed by #pkuzhel.
Look at this codesandbox example to see it in action.
#Andrey
Would you try this below code? and let me know if that resolves your issue.
import React, { Component } from 'react';
import { Input, Button } from 'semantic-ui-react'
class App extends Component {
clear = () => {
console.log(this.inputRef.target.value);
this.inputRef.target.value = '';
}
render() {
return (
<div className="App">
<Input placeholder='Search...' onChange={(input) => {input.persist(); this.inputRef = input}} />
<Button onClick={this.clear}>Clear</Button>
</div>
);
}
}

Categories

Resources