I am trying to do a custom label for my barchart using <LabelList> component.
This is my LabelList component and the corresponding render content function:
<LabelList
dataKey='pv'
position='insideRight'
fill='#f5f5f5'
className={'chart-label'}
offset={15}
content={renderLabel}
/>
const renderLabel = function(props: LabelProps){
return `${props.value}%`;
};
I just need to append a % symbol at the end of the chart value. but this is not working.
I used formatter prop for <LabelList> component instead of content prop.
<LabelList
dataKey='pv'
position='insideRight'
fill='#f5f5f5'
className={'chart-label'}
offset={15}
formatter={renderLabel}
/>
const renderLabel = (props: any) => {
return `${props}%`;
};
Yes using formatter for this is correct when you just want to affect the raw label text. The content property/api should be used if you want to provide the full markup for the label itself with full freedom to do what ever you like, and can be set to another react component, or to a function which must return the result from JSX rendering
Heres an example for other who stumbles across this blog and might need to use the 'content' freedom.
Use LabelList with content set to function which returns rendered JSX
<LabelList
content={renderLabelContent}
/>
The function:
const renderLabelContent = (props: object) => {
const { x: number, y, width, height, value } = props;
return (
<div>
{// All kinds of custom JSX/html here}
{value}
</div>
);
};
Using it with another selfmade react component (CustomizedLabel), you can pass in properties and values;
<LabelList
content={<CustomizedLabel external={external} />}
/>
Related
I'm trying to implement a simple dark/light theme toggle to my website. In my base App.tsx I've implemented the state I use:
const [colorScheme, setColorScheme] = useState("light");
I pass that "colorScheme" variable as a prop to every other element. The theme toggle is contained in a header element, so I also pass the "setColorScheme" function to header as a prop. Within Header.tsx, the code triggered when the toggle is clicked is:
setColorScheme(s => s === "dark" ? "light" : "dark");
Within every specific element, I set the color scheme like so:
<ElementName className={"element_name element_name_"+colorScheme}/>
I have all the css for styling the component contained in the class "element_name", and then all relevant color data is contained in "element_name_light" or "element_name_dark".
When the toggle in the header is clicked, a re-render is triggered for the main body of the app, and for the header. But all of the other elements do not re-render. If I navigate to another element, the re-render happens and the color scheme appears as intended.
Attached is a gif of this happening.
I'm still learning React, so I'm sure it's something obvious I'm missing. I would appreciate any tips anyone can provide! Thanks
One note: I am using react functionally, rather than implementing classes for each component.
It's impossible to tell exactly what mistake you made since you haven't shared your code. But I can tell you the root mistake is not using React's context API. This will allow you to hold the color scheme and the toggle function as a global state and import them into every component via the useContext hook.
Here's an example on stackblitz: https://stackblitz.com/edit/react-ts-lhwstv?file=color-scheme-ctx.tsx
Here's the docs: https://reactjs.org/docs/context.html
Note: I'm using typescript, if you're using plain javascript just remove the type declarations and the generic typings <Type>.
You start by creating the context and giving a default value:
type ColorScheme = 'light' | 'dark';
type Props = { colorScheme: ColorScheme; toggleColorScheme: () => void };
export const ColorSchemeCtx = createContext<Props>({
colorScheme: 'light',
toggleColorScheme: () => {},
});
I like to then create a provider component for organization.
export const ColorSchemeCtxProvider: FC<PropsWithChildren<{}>> = ({
children,
}) => {
const [colorScheme, setColorScheme] = useState<ColorScheme>('light');
function toggleColorScheme() {
setColorScheme((s) => (s === 'dark' ? 'light' : 'dark'));
}
return (
<ColorSchemeCtx.Provider value={{ colorScheme, toggleColorScheme }}>
{children}
</ColorSchemeCtx.Provider>
);
};
Then wrap all components that need the context - probably just put it at the highest level possible.
root.render(
<StrictMode>
<ColorSchemeCtxProvider>
<App />
</ColorSchemeCtxProvider>
</StrictMode>
);
Now any component can get both the color scheme and / or the toggle function with useContext
export default function App() {
const { colorScheme, toggleColorScheme } = useContext(ColorSchemeCtx);
return (
<div>
<p>The color scheme is: {colorScheme}</p>
<button onClick={toggleColorScheme}>TOGGLE</button>
<CompOne />
<CompTwo />
<CompThree />
</div>
);
}
export default function CompOne() {
const { colorScheme } = useContext(ColorSchemeCtx);
return <div className={'comp-one ' + colorScheme}></div>;
}
I am beginner developer and I am working on react (gatsby, TS, styled components) project. I am getting this error:
"React does not recognize the isOpen prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase isopen instead. If you accidentally passed it from a parent component, remove it from the DOM element."
export const Navigation = () => {
const [isNavigationOpen, setIsNavigationOpen] = useState(false);
const { isTablet } = useQuery();
const showNavbar = () => {
setIsNavigationOpen((previousState) => !previousState);
};
const renderElement = isTablet ? (
<>
<SvgStyled
src='bars_icon'
isOpen={isNavigationOpen}
onClick={showNavbar}
/>
<MobileNavigation isOpen={isNavigationOpen}>
{NAVIGATION_DATA.map(({ id, url, text }) => (
<LinkMobile key={id} to={url}>
<ExtraSmallParagraph>{text}</ExtraSmallParagraph>
</LinkMobile>
))}
</MobileNavigation>
</>
) : (
<FlexWrapper>
{NAVIGATION_DATA.map(({ id, url, text }) => (
<LinkDekstop key={id} to={url}>
<ExtraSmallParagraph>{text}</ExtraSmallParagraph>
</LinkDekstop>
))}
</FlexWrapper>
);
return renderElement;
};
I am sure that I am missing some fundamental react stuff or something. Maybe someone could help me and explain the reason of this error.
When this happens it is because all props passed to the styled component are then also passed down to the DOM element that you are styling.
You've likely a component that looks like the following:
const SvgStyled = styled(SVG)<{ isOpen: boolean }>`
// your CSS and logic referencing the `isOpen` prop
`;
To resolve this issue you refactor the styled component definition and explicitly pass only the props you want to the element being styled. Use an anonymous function component and destructure the prop you don't want to pass on to the DOM element, and spread the rest of the props. This ensures the className prop that styled-components is creating a CSS class for is passed through.
Example:
interface SvgStyledProps {
className?: string,
isOpen: boolean,
}
const SvgStyled = styled(({ isOpen, ...props}) => (
<Svg {...props} />
))<SvgStyledProps>`
// your CSS and logic referencing the `isOpen` prop
`;
For any other Typescript specifics/caveats with styled-components see docs.
As of styled components v5.1, you can alternatively prevent undesired props from being passed down to your React node by prefixing it with a dollar sign ($) and designating it as a transient prop:
const SvgStyled = styled(SVG)<{ $isOpen: boolean }>`
// your CSS and logic referencing the `$isOpen` prop
`;
// SVG does NOT receive props.$isOpen
docs
I am learning react by coding a gamertag generator. It generates random tags and keeps a list, and each can be rated. My main app is a functional component utilizing the useState hook to set state: an array of objects with details about the tags, namely a star rating system.
I generate each gamertag using a react component Tag, within, it uses a functional component, RenderStars to draw the stars. Each tag stars off with 0 stars, so 5 empty stars, and I want the user to change rating by clicking on however many stars, 1-5. RenderStars will then draw however many empty and filled stars as needed.
I have a function in App, changeStars, that I can't seem to get any of the child components to call successfully. I am passing the function to the child components through props.
I've tried writing changeStars in arrow notation and as a plain function. I've tried it without requiring any parameters. I've tried calling it within Tag just using a button. There's other ways I've messed with it that I can't quite recall, just messing with the syntax and trying other things from stackexchange and articles.
I don't bind the function because it's created in a functional component.
This seems like a super basic task and I can't figure it out. Yes i've read the Docs from react.js
Here is some of the code, I'll try to take out as much as possible:
function App() {
const [tagInventory, setTagInventory] = useState([]);
const latestTag = tagInventory[tagInventory.length - 1] ? tagInventory[tagInventory.length -1] : null;
const handleAdd = (tag) => {
uses hook to add tag to state
}
const makeTag = () => {
creates random tag
}
function changeStars(stars,key) {
console.log(stars, key);
//this will change the star rating of an individual tag
}
return (
<main>
A bunch of amazing interface html
<section className="tagInventory">
{tagInventory.map( (item) =>
<Tag
key={item.timeStamp}
tagItem={item}
/>
) }
</section>
</main>
);
};
class Tag extends React.Component {
render() {
const item = this.props.tagItem;
const stars = this.props.tagItem.stars;
const key = this.props.tagItem.timeStamp;
const tagClass = this.props.newTag ? "tag-item new-item" : "tag-item";
return (
<div className={tagClass}>
code to generate cool tag info
</div>
<RenderStars
stars={stars}
changeStars={changeStars}
newTag={false}
key={key}
/>
</div>
);
}
}
const RenderStars = (props) => {
// ref for using symbol tag https://css-tricks.com/svg-symbol-good-choice-icons/
return (
i load svg of stars then can display as many as i need later...
now i draw 4 stars, for the example i'll stop at the first, here's the call..
{props.stars === 0 &&
<div>
<svg className="empty-star" onClick={() => props.changeStars(4,props.key)}>
<use xlinkHref="#empty-star" />
now the other stars and whatnot
}
Thanks!
So basically you want to pass the function changeStars from App to Tag and then to RenderStars, is that correct?
If so, you're forgetting to pass it from App to Tag
App:
<section className="tagInventory">
{tagInventory.map( (item) =>
<Tag
key={item.timeStamp}
tagItem={item}
/>
) }
</section>
Should be passing the function:
<section className="tagInventory">
{tagInventory.map( (item) =>
<Tag
key={item.timeStamp}
tagItem={item}
changeStars={changeStars}
/>
) }
</section>
And then on Tag:
const changeStars = this.props.changeStars;
Is it possible to style the grouping row that you can see in the attached screenshot? What I would like to do is provide a React component that is rendered in place of that.
Here is the codesandbox for the attached screenshot.
The screenshot shows that the class of the div that represents that grouping row is react-grid-row-group, and the only place this appears in the React-Data-Grid codebase is in RowGroup.tsx.
const RowGroup = forwardRef<HTMLDivElement, Props>(function RowGroup(props, ref) {
function onRowExpandToggle(expand?: boolean) {
const { onRowExpandToggle } = props.cellMetaData;
if (onRowExpandToggle) {
const shouldExpand = expand == null ? !props.isExpanded : expand;
onRowExpandToggle({ rowIdx: props.idx, shouldExpand, columnGroupName: props.columnGroupName, name: props.name });
}
}
function onRowExpandClick() {
onRowExpandToggle(!props.isExpanded);
}
function onClick() {
props.eventBus.dispatch(EventTypes.SELECT_CELL, { rowIdx: props.idx, idx: 0 });
}
const lastColumn = props.columns[props.columns.length - 1];
const style = { width: lastColumn!.left + lastColumn!.width };
const Renderer = props.renderer || DefaultBase;
return (
<div className="react-grid-row-group" style={style} onClick={onClick}>
<Renderer {...props} ref={ref} onRowExpandClick={onRowExpandClick} onRowExpandToggle={onRowExpandToggle} />
</div>
);
});
export default RowGroup;
So it seems that if that component receives a renderer prop, it will use it to render the group row under the div with aforementioned class name.
Usages of RowGroup.tsx are basically in Canvas.tsx, and Canvas instantiates RowGroup with the renderer prop being this.props.rowGroupRenderer. Canvas is rendered in Viewport.tsx. Viewport is rendered in Grid.tsx, and Grid is rendered in ReactDataGrid.
In the docs for React-Data-Grid we see the prop rowGroupRenderer described as
rowGroupRenderer
Function called whenever keyboard key is pressed down
type: func
However as described in the question above, looking at the code, we can see that this prop controls also what the row looks like when you have a group.
However, one question that remains is why this prop is not available in the TypeScript type definitions for the props of ReactDataGrid?
I'd like part of the record to be included in the label for a BooleanField (and BooleanInput). I'm trying to use WithProps to accomplish this.
If I use
<BooleanField source="FileSystem" label="FileSystem" />
This seems to work just fine. If, instead I try to wrap it
const makeLabel = (props)=>{
let label = `Filesystem for ${props.record.id}`;
return {label};
}
const withLabel = withProps(makeLabel);
const BooleanFieldWithLabel = compose(withLabel)((props)=>{
console.log("props after compose",props);
return <BooleanField {...props}/>
});
And then use <BooleanFieldWithLabel source="FileSystem" /> It doesn't render any label. I've tried a few different ways and nothing seems to work even though I can see in the console.log that the correct label is in props. What am I doing wrong here?
I have the same question, I cannot display the label base on field's value on "Show" page.
From react-admin source code, it seems only I set "addLabel" prop on the direct child of "SimpleShowLayout" or "TabbedShowLayout", then I can see label on my custom field.
But it is not configurable, I want to show/hide label base on field's value. Do I need to implement my own custom "SimpleShowLayout" or "TabbedShowLayout"? Or is there any better approaches?
Update my post.
I just figure out the solution by implementing an HOC like below. I am wondering is there any better approaches to implement the same feature?
import React from "react";
import get from "lodash/get";
import { TextField, DateField, Labeled } from "react-admin";
const NullableField = WrappedComponent => props => {
const { record, source } = props;
const value = get(record, source);
return value ? (
<Labeled {...props}>
<WrappedComponent {...props} />
</Labeled>
) : null;
};
const NullableTextField = NullableField(TextField);
const NullableDateField = NullableField(DateField);
export { NullableTextField, NullableDateField };